这可以被认为是一个家庭作业问题。这个问题是众所周知的:"you have a triangle of numbers and you have to find the greatest sum“
好吧,没问题,不久前我用python做了一个解决方案,运行完美无瑕。但现在在c++中,解决方案是75256,我的答案是9729。所以问题是类型short溢出。
因此,为了解决这个问题,我假设将数组更改为int类型就可以解决所有问题。但是,当声明一个数组a[1001][1001]时,它会冻结(我猜是内存错误)。
有人知道该怎么做吗?我尝试了另一个整数,当a中的值大于32767时,它就会递增,但我的解决方案仍然是OFF300?(代码可以工作-在许多较小的上进行了测试)
#include <iostream>
#include <fstream>
int main() {
std::ofstream fout ("numtri.out");
std::ifstream fin ("numtri.in");
short trifield[1001][1001] = {0};
int Rows, tmp=0;
fin >> Rows;
for (int x = 0; x<Rows;x++)
for (int nr = 0; nr<=x;nr++){
fin >> tmp;
trifield[x][nr] = tmp;}
for (int y = (Rows-2); y > -1; y--)
for (int x = 0; x <= y+1; x++) {
int a = trifield[y+1][x];
int b = trifield[y+1][x+1];
if (a > b) trifield[y][x] += a;
else trifield[y][x] += b;
}
fout << trifield[0][0] << std::endl;
return 0;
}注意:我不是在寻找解决方案,只是想要一个处理溢出的好方法,感谢你的例子!
发布于 2011-05-24 02:39:02
你得到的是堆栈溢出而不是数字溢出!
将数组移到main之外的静态内存中,这样它就不会使用堆栈。
发布于 2011-05-24 02:33:02
如果你有内存问题,尝试动态分配你的数组:
short** trifield = new short[1001][1001];发布于 2011-05-24 02:34:26
你有一组1001x1001的短裤...这是1002001*2字节。这些都会传到你的local stack上。这可能太大了,这取决于您的系统。尝试使用malloc为您的“trifield”分配空间。看看这对你有什么好处
https://stackoverflow.com/questions/6101297
复制相似问题