【问题标题】:USACO number triangle - Execution errorUSACO 数字三角形 - 执行错误
【发布时间】:2012-03-15 11:28:03
【问题描述】:

问题如下

考虑下面显示的数字三角形。编写一个程序,计算可以在从顶部开始到底部某处结束的路线上传递的最大数字总和。每一步都可以向左斜向下或向右斜向下。

      7

    3   8

  8   1   0

2   7   4   4

4 5 2 6 5 在上面的示例中,从 7 到 3 到 8 到 7 到 5 的路线产生的总和最大:30。

我遇到了以下错误

Your program had this runtime error: Bad
syscall #32000175 (RT_SIGPROCMASK) [email kolstad if you think
this is wrong]. The program ran for 0.259 CPU seconds before the
error. It used 16328 KB of memory.

代码如下。

int arr[1500][1500];
map < int,map < int,int> >dp;

int main()
{
    // ofstream fout ("numtri.out");
    // ifstream fin ("numtri.in");
    int n;
    // fin>>n;
    freopen ("numtri.in", "r", stdin);
    freopen ("numtri.out", "w", stdout);
    scanf ("%d", &n);
    int ct = 1;
    int gaga = -100;
    for (int i=0; i<n; i++)
    {
        for (int j=0; j<ct; j++)
        {
            scanf ("%d", &arr[i][j]);
            if(i>0)
                dp[i][j] = maxi (dp[i-1][j-1] + arr[i][j], dp[i-1][j] + arr[i][j]);
            else
                dp[0][0]=arr[0][0];
            if (i == n-1)
            {
                if (dp[i][j] > gaga)
                    gaga=dp[i][j];
                }
        }
        ct++;
    }
    printf ("%d\n", gaga);
    return 0;
}

它在我的笔记本电脑上运行良好。在网站上,它适用于 8 个测试用例,第 9 个测试用例失败并出现此错误。

感谢您的帮助!

【问题讨论】:

    标签: algorithm optimization dynamic-programming


    【解决方案1】:
     if(i>0)
         dp[i][j]=maxi(dp[i-1][j-1]+arr[i][j],dp[i-1][j]+arr[i][j]);
    

    您检查i &gt; 0,这将确保您永远不会访问负索引。但是,您永远不会对 j 做同样的事情,因此您将在第一次运行内部 (j) 循环时访问 dp[i-1][-1]。我很确定这是导致错误的原因。

    【讨论】:

    • +1 这似乎很有可能。通常 DP 解决方案从初始化极端情况开始,然后从下一项继续迭代(在这种情况下,两个for 循环都应该从 1 开始),这样就避免了每次迭代都检查索引值的需要。我也不知道为什么dp 是map,而不是一个普通的数组。
    • 我使用了一张地图,因此所有负指数都为零,我不需要照顾它..
    猜你喜欢
    • 2013-05-20
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多