【发布时间】:2013-05-20 23:16:45
【问题描述】:
问题如下
考虑下面显示的数字三角形。编写一个程序,计算可以在从顶部开始到底部某处结束的路线上传递的最大数字总和。每一步都可以向左斜向下或向右斜向下。
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
在上面的示例中,路由 7 -> 3 -> 8 -> 7 -> 5 产生最高和:30。
我遇到了以下错误
Execution error: Your program (`numtri') used more than the
allotted runtime of 1 seconds (it ended or was stopped at 1.674
seconds) when presented with test case 6. It used 6080 KB of
memory.
我的程序适用于输入
这是我的代码:
#define MAX 1000
int max=0,a[MAX][MAX];
void dfs(int i,int j,int end,int sum)
{
if(i<=end)
{
sum += a[i][j];
dfs(i+1,j,end,sum);
dfs(i+1,j+1,end,sum);
}
else
{
if(sum>max)
max = sum;
}
}
int main () {
FILE *fin = fopen ("numtri.in", "r");
FILE *fout = fopen ("numtri.out", "w");
int r,i,j;
fscanf(fin,"%d",&r);
for(i = 1;i<=r;i++)
for(j = 1;j<=i;j++)
fscanf(fin,"%d",&a[i][j]);
dfs(1,1,r,0);
fprintf(fout,"%d\n",max);
fclose(fin);
fclose(fout);
return 0;
}
它适用于前 5 个测试用例,但在第 6 个测试用例失败,它有 199 个三角形大小。
【问题讨论】:
-
向 DFS 添加 memoization 或使用动态编程可以使您的程序更快。因为对于固定的i,j,从(i,j)到底部的最优路径也是固定的。因此,一对 (i,j) 只需要一个 DFS。如果您需要第二次 DFS,只需使用之前搜索的结果即可。
-
我在这里写这篇文章是因为它与你的问题没有直接关系,但如果你想做编程(尤其是像 topcoder 之类的东西),你真的应该学习算法和数据结构。许多 [谁?] 认为有关该主题的规范书籍是 Cormen 等人的算法简介,我建议你拿起它。
-
如果我没记错的话,如果
r是1000你的程序会调用未定义的行为...
标签: c algorithm optimization data-structures depth-first-search