我忙于Project Euler,我正在尝试解决problem 11,但答案似乎有问题。但我不明白为什么,代码似乎是正确的。
vector<vector<int> > grid;
ifstream stream("/home/uauser/workspace/Project_euler/grid.txt");
string line;
char *tok;
if (stream.is_open())
{
while(stream.good())
{
getline(stream, line);
tok = strtok((char *)line.c_str(), " ");
vector<int> row;
while (tok != NULL)
{
int field;
stringstream ss;
ss << tok;
ss >> field;
row.push_back(field);
tok = strtok(NULL, " ");
}
grid.push_back(row);
}
stream.close();
}
int product = 0;
for(unsigned int i = 0; i < grid.size(); i++)
{
for(unsigned int j = 0; j < grid.at(i).size(); j++)
{
if( i < 17)
{
product = max(product, grid.at(i).at(j) * grid.at(i + 1).at(j) * grid.at(i + 2).at(j) * grid.at(i + 3).at(j));
}
if( j < 17)
{
product = max(product, grid.at(i).at(j) * grid.at(i).at(j+1)* grid.at(i).at(j+2) * grid.at(i).at(j + 3));
}
if((j < 17) && (i < 17) && (j >= 3) && (i >= 3))
{
product = max(product, grid.at(i).at(j) * grid.at(i-1).at(j+1) * grid.at(i-1).at(j+2) * grid.at(i -3).at(j+3));
product = max(product, grid.at(i).at(j) * grid.at(i+1).at(j-1) * grid.at(i+1).at(j-2) * grid.at(i +3).at(j-3));
product = max(product, grid.at(i).at(j) * grid.at(i+1).at(j+1) * grid.at(i+1).at(j+2) * grid.at(i + 3).at(j + 3));
product = max(product, grid.at(i).at(j) * grid.at(i-1).at(j-1) * grid.at(i-1).at(j-2) * grid.at(i -3).at(j-3));
}
cout<<product<<endl;
}
}
cout<<"The Product is: "<<product<<endl;
}
播放代码读取的txt文件没有问题,但是当他需要找到最大值时才会得到错误的答案。
答案 0 :(得分:5)
对角线的指数是错误的。例如:
... * grid.at(i-1).at(j+1) * grid.at(i-1).at(j+2) * grid.at(i -3).at(j+3))
中间部分应该有i-2
而不是i-1
。与其他对角线类似的问题。