[英]Why does this C++ code give different output on different compilers?
我意識到關於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 = "";
}
(如果有任何不同,我提交的完整代碼在這里 。)
編輯:
萬一有人偶然發現此代碼以尋找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 ...”。
在codeforce服務器和本地工作站上,程序的輸出均為“ 4 3 2 3 4 3 ...”。
因此您的算法是錯誤的,並且程序的輸出是一致的。
您正在混合測試結果“輸出”和“答案”的兩個字段。
再次檢查測試結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.