Pat*_*ins 1 c++ compiler-construction algorithm gcc c++11
我意识到在SO上有很多关于这个标题的问题,但是我发现的所有问题都有类似的东西,i = ++i或者f(f(f(x)))都没有在这个代码中.这是在回溯解决方案的尝试这个.我有一些C的经验,但我刚开始尝试学习C++,而且我一直在为练习做Codeforces问题.下面的代码段是该程序的主体.main我没有展示,处理输入和输出.我使用的全局变量这里weights,answer以及max_depth在保持的每个堆栈帧的利益solve尽可能小.
引起麻烦的输入是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 = "";
}
Run Code Online (Sandbox Code Playgroud)
(我提交的完整代码,如果有任何区别,就在这里.)
编辑:
万一有人偶然发现这个问题,寻找Codeforces问题的答案:这个代码的问题是"回答"是相反的.更改answer.append(ss.str() + " ")为answer = ss.str() + answer最短的修复程序,使其工作.
为什么这个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 ......",这是不正确的.
我相信你在codeforces服务器上误解了你的测试结果.
正确答案是"9 10 9 10 ......".
代码服务器和本地工作站上的程序输出为"4 3 2 3 4 3 ...".
所以你的算法是错误的,程序的输出是一致的.
您正在混合测试结果"输出"和"答案"上的两个字段.
再次检查您的测试结果.