【问题标题】:Strange program behavior奇怪的程序行为
【发布时间】:2014-12-29 23:10:53
【问题描述】:

所以我想编写解决这个问题的代码:“Collecting Beepers” 我做到了:

int rec(int current, int beers)
{
    if(beers == (1 << (numOfBeers + 1)) - 1) return cost(beerX[0], beerY[0], beerX[current], beerY[current]);
    int optimal = 100000;
    for(int i = 1; i <= numOfBeers; ++i)
    {
        if(((1 << i) & beers) == 0)
        {
            int newBeersSet = (1 << i) | beers;
            int c = cost(beerX[current], beerY[current], beerX[i], beerY[i]);
            int current = c + rec(i, newBeersSet);
            optimal = min(optimal, current);
        }
    }
    return optimal;
}

奇怪的是,当我更换零件时

int c = cost(beerX[current], beerY[current], beerX[i], beerY[i]);
int current = c + rec(i, newBeersSet);

int current = cost(beerX[current], beerY[current], beerX[i], beerY[i]) + rec(i, newBeersSet);

逻辑是完全一样的,但是我的程序在相同的输入(问题描述中给出的那个)上崩溃,并且在线法官给出了错误的答案作为程序执行的结果,而它给出的原始代码被接受。有什么想法可能是错误的吗?

【问题讨论】:

  • 您是否验证过costrec 之前仍被调用?
  • 到底是哪一行崩溃了?

标签: c++


【解决方案1】:

这可能是因为您的变量“current”被覆盖了。试试:

int current2 = cost(beerX[current], beerY[current], beerX[i], beerY[i]) + rec(i, newBeersSet);
optimal = min(optimal, current2);

【讨论】:

    【解决方案2】:

    在这一行中,您使用了一个未初始化的变量:

    int current = cost(beerX[current],  // ...
    

    这会声明一个新变量current,然后在为变量赋值之前,将其用作beerX 的索引。

    你的意思可能是:

    int new_current = cost(beerX[current],  // ...
    

    它使用在rec 函数的参数列表中声明的现有current 变量。

    【讨论】:

      猜你喜欢
      • 2017-01-17
      • 2014-05-11
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 2011-03-13
      相关资源
      最近更新 更多