什么导致了产量的差异?

Ola*_*nka 3 c++ runtime-error

在CodinGame.com上解决了这个问题,我设法编写了一个代码,通过了最后一个测试用例的系统测试(一个非常大的测试用例).但是在我的笔记本电脑上编译我得到的输出为0而不是57330892800,代码从他们的机器给我.我用Visual Studio 2012 Express和Dev C++ 4.9.9.2编译.

我使用了一个递归函数,所以如果我的堆栈内存不足,我就会发现堆栈溢出错误,但是没有错误,没有错误,只有0的输出.为什么这会在我的系统上发生,而它工作得很好该网站的机器?什么可能导致这一点,我怀疑它是堆栈溢出?

#include<iostream>
#include<algorithm>
#include<stack>
#include<string>
#include<map>
#include<set>
#include<vector>

using namespace std;
typedef long long LONG;


string X[]={".-","-...","-.-.","-..",
            ".","..-.","--.","....",
            "..",".---","-.-",".-..",
            "--","-.","---",".--.",
            "--.-",".-.","...","-",
            "..-","...-",".--","-..-",
            "-.--","--.."};
map<string, int> dict;

string morse(const string ret){
        string s;
        for(char c : ret) s+=X[c-'A'];
        return s;
}

LONG decode(int start, string &word, vector<LONG> &mem){
        if(start == word.size()) return 1;
        else if(mem[start] != -1) return mem[start];

        LONG res = 0;
        string s;
        for(int i=0; i<19*4 && start+i<word.size(); i++){
                s+=word[start+i];
                auto curr = dict.find(s);
                if(curr!=dict.end()) res+=curr->second*decode(start+i+1, word, mem);
        }
        mem[start]=res;
        return res;
}

int main(){
        string word;
        cin>>word;
        int n; cin>>n;
        for(int i=0; i<n; i++){
                string s;
                cin>>s;
                dict[morse(s)]++;
        }
        vector<LONG> mem(word.size(), -1);
        cout<<decode(0, word, mem)<<endl;
}
Run Code Online (Sandbox Code Playgroud)

gx_*_*gx_ 6

我认为我已经设法将你的代码剥离到一个最小的程序:

#include<iostream>
#include<string>

using namespace std;

int main(){
        string word;
        cin>>word; // or getline(cin, word);
        cout << word.size() << endl;
}
Run Code Online (Sandbox Code Playgroud)

测试用例输入文件的结果:

  • 在Codingame(with test=4)上,它打印9884(如预期的那样).
  • 在我的个人计算机上,在prog从终端命令行(控制台)将源文件编译为名为" " 的二进制文件之后:
    1. 如果我运行./prog然后文件中的文本复制粘贴到控制台中,则会打印4095(错误).
    2. 如果我./prog < Test_4_input.txt改为跑,那么打印9884(好).

我假设你做了相当于1.(从你的IDE启动程序并将文本粘贴到其"控制台"选项卡),而Codingame"就像"2.因此你得到了这里描述的问题:Linux终端输入:阅读来自终端截断行的用户输入为4095字符限制(读取缓冲区似乎具有4096字节的大小限制(并使用最后一个用于换行符,因此截断为4095)).


编辑:至于我是怎么发现的:

和你一样,我开始在IDE(Eclipse)中运行程序并将文件内容复制粘贴到嵌入式输入控制台中,0结果我也得到了.所以我开始调整代码并在IDE中调试它.

我首先添加了一个全局计数器(初始化为0),在第一行增加decode并在末尾打印main,以查看调用该函数的次数.它的最终价值1254在于Codingame,但仅限541于我的IDE.
所以我设置一个条件断点decode增量刚过(条件:计数器== 541),启动了调试器和代码中的阶梯,只见那环是早终止.然后我看着局部变量,我注意到word有一个size4095.我发现它"有趣",因为它是4096减1并且4096是2的幂; 你知道,就像你看到的那样255.
所以我打开了一个文本编辑器,只复制粘贴输入文件的第一行,看到它的长度不是4095而是9884.现在我开始意识到这个问题了.所以我将代码剥离到上面显示的最小测试用例,然后切换到命令行终端进行检查(看到Codingame显示使用Bash测试脚本solution < in$test.txt),并在网上搜索了一些类似问题的引用(如上面的链接问题)."拼图解决了."

希望这将有助于您自己解决未来的问题:)