This could be considered a homework question. This problem is wel known: "you have a triangle of numbers and you have to find the greatest sum"
well no problem, I've made a solution in python some time ago, works flawless.
But now in c++, the solution is 75256, my answer is 9729.
So the problem is that the type short overflows.
So to fix this, I assumed changing my array to type int would solve everything.. but then, when declaring an array a[1001][1001] it freezes (i guess memory error).
anyone know what to do?
I tried something with another int, and whenever the value in a got bigger than 32767 it would increment, but my solution then still is off 300? (the code works - tested on many smaller ones)
#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;
}
note: I'm not looking for the solution, just a good way to deal with overflows, examples appreciated!
intwill result in error