问题描述
当我为问题农民剧 - AIO 2016 (https://orac.amt.edu.au/cgi-bin/train/problem.pl?set=aio16int&problemid=903) 运行以下代码时,
#include <bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//freopen("farmin.txt","r",stdin);
//freopen("farmout.txt","w",stdout);
int n; cin >> n;
vector<int> p(n);
for (int i=0; i<n; i++) {
cin >> p[i];
}
int f=p[0],l=p[n-1],i1=0,i2=n-1,c=0;
while (i1!=i2) {
if (f==l) {
--i2; ++i1;
f = p[i1]; l = p[i2];
continue;
}
if (f<l) {
++i1;
f = f+p[i1];
c++;
}
if (l<f) {
--i2;
l = l+p[i2];
c++;
}
}
cout << c << '\n';
return 0;
}
终端返回 shell 返回 -1073741819 即使逻辑非常好。确切的错误消息如下:
C:\WINDOWS\system32\cmd.exe /c (AIO\2016\farmer)
6
1 1 1 1 1 1
shell returned -1073741819
Hit any key to close this window...
如果我运行不同的输入,例如:
8
1 2 2 5 1 3 1 1
它运行得非常好并返回正确的输出:3.
这种情况经常发生,但我不知道是什么原因造成的。你能帮我吗,因为这很令人沮丧?
解决方法
我针对 AddressSanitizer 运行了这段代码;您遇到了分段错误,因此您的 shell 以奇怪的返回码退出。
问题出在这一行:
f = p[i1]; l = p[i2];
针对提供的错误示例运行代码时,i1
的值为 6
,这会导致溢出;并且 i2
的值为 -1。
尝试通过在 while 循环中添加另一个条件来防止这种情况,例如:
while(i1 > -1 && i1 != i2)
但是我还没有测试过这个,这将防止错误,但我不确定它是否给出了正确的答案。