执行后,我的代码给出的退出状态为-1。我可以显示输入是否有任何区别。有人能找到原因吗?
输入:
6
N 10
2号
3号
4号
5号
8号
我已经查看了2D整数数组和代码中的变量,寻找未初始化的变量,但没有发现此类错误。有人可以看到我为什么要获得退出状态-1吗?
#include <iostream>
#include <algorithm>
#include <fstream>
using namespace std;
int main() {
ofstream fout("mowing.out");
ifstream fin("mowing.in");
int n; fin >> n;
int ans = 0;
int field[2003][2003];
for (int i = 0; i < 2003; i++) {
for (int j = 0; j < 2003; j++) {
field[i][j] = 0;
}
}
int xloc = 1001, yloc = 1001, time = 0;
for (int i = 0; i < n; i++) {
char dir; int steps;
fin >> dir >> steps;
if (dir == 'N') {
for (int j = 1; j < steps; j++) {
yloc++;
time++;
if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
field[xloc][yloc] = time;
}
}
if (dir == 'S') {
for (int j = 1; j < steps; j++) {
yloc--;
time++;
if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
field[xloc][yloc] = time;
}
}
if (dir == 'W') {
for (int j = 1; j < steps; j++) {
xloc--;
time++;
if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
field[xloc][yloc] = time;
}
}
else {
for (int j = 1; j < steps; j++) {
xloc++;
time++;
if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
field[xloc][yloc] = time;
}
}
}
if (ans == 0) fout << -1 << "\n";
else fout << ans << "\n";
return 0;
}
最佳答案
除了bruno提出的优点之外,我相信您遇到的问题的根本原因是(nomen预兆!)堆栈溢出。
您的数组太大,无法放在堆栈上。快速计算(假设sizeof(int) == 4
):
2003 * 2003 * 4 B = 16048036 B = 15671.91015625 KiB = 15.304599761962890625 MiB
您正在尝试在堆栈上分配15.3 MiB的内存,而根据this question,默认情况下Windows允许1 MiB,而Linux通常允许8 MiB。
您应该自己在堆上分配内存,或者(最好)使用
std::vector
,如下所示:std::vector<std::vector<int>> field (2003, std::vector(2003));
//it is already initialized above, no need for for loops ;)
//later on it can be used like regular array in most of the cases