2013-08-30 75 views
1

我意识到这个标题有很多问题,但我发现的所有问题都做了如i = ++if(f(f(x))),这两个都不在此代码中。这是对this的回溯解决方案的尝试。我对C有一些经验,但是我刚开始尝试使用C++,而且我一直在为实践做一些Codeforces问题。下面的代码片段是程序的主体。我没有示出的main涉及输入和输出。为了使每个堆栈帧solve尽可能小,我在此使用了全局变量weights,answermax_depth为什么此C++代码在不同的编译器上提供不同的输出?

导致问题的输入是weights = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}max_depth = 1000。当我用g++ std=C++11 file.cpp编译时,它给出了“4 3 2 3 4 3 2 3 4 ... 3 2 1”,这是正确的答案。当Codeforces编译它时,它会显示“9 10 9 10 9 10 9 10 ...”,这是不正确的。我的猜测是,for(int i : weights)遍历向量的顺序并未由标准定义,但即使如此,我也不明白为什么它会产生任何影响。我错过了什么?

#include <iostream> 
#include <vector> 
#include <sstream> 

using namespace std; 

string answer = ""; 
vector<int> weights; 
int max_depth; 

bool solve(int left_scale, int right_scale, int last_added, int depth){ 
    bool is_left = (depth % 2) == 0; 

    int new_weight; 
    int weight_to_inc = is_left ? left_scale : right_scale; 
    int weight_to_exceed = is_left ? right_scale : left_scale; 

    if (depth == max_depth){ 
    return true; 
    } 


    for(int i : weights){ 
    if (i != last_added){ 
     new_weight = weight_to_inc + i; 
     if (new_weight > weight_to_exceed){ 
     bool ans = solve(is_left ? new_weight : left_scale, 
          is_left ? right_scale : new_weight, 
          i, depth + 1); 
     if (ans){ 
      stringstream ss; 
      ss << i; 
      answer.append(ss.str() + " "); 
      return true; 
     } 
     } 
    } 
    } 

    return false; 
} 

void start_solve(void){ 
    if (solve(0, 0, 0, 0)){ 
    return; 
    } 

    answer = ""; 
} 

(完整的代码,我提出,如果这有什么差别,是here

编辑:

万一有人在此寻找一个答案Codeforces问题绊倒:这个代码的问题是“答案”是相反的。将answer.append(ss.str() + " ")更改为answer = ss.str() + answer是使其工作的最短的修复程序。

+6

没有看代码,答案可能在于你做了什么导致未定义的行为。 –

+0

主要功能在哪里? –

+0

顺便说一下,基于范围的'for'语句迭代的顺序非常好定义,因为它使用场景后面的普通迭代器。见例如[here](http://en.cppreference.com/w/cpp/language/range-for)了解它的工作原理。 –

回答

7

为什么这个C++代码在不同的编译器上给出不同的输出?

它没有给出不同的输出。

当我用g ++ std = C++ 11 file.cpp编译时,它给出了“4 3 2 3 4 3 2 3 4 ... 3 2 1”,这是正确的答案。当Codeforces编译它时,它会显示“9 10 9 10 9 10 9 10 ...”,这是不正确的。

我相信你误解了your test results on the codeforces server

正确答案是“9 10 9 10 ...”。

你的程序的输出是“4 3 2 3 4 3 ...”在codeforces服务器和你的本地工作站上。

所以你的算法是错误的,程序的输出是一致的。

您正在混合测试结果“输出”和“答案”上的两个字段。

再次检查您的测试结果。

+0

啊,我是白痴然后,谢谢。 –

相关问题