gpt4 book ai didi

c - codechef 练习题中的运行时错误

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:51 27 4
gpt4 key购买 nike

我收到“sigsegv”,当我尝试在 codechef 上运行以下代码时出现运行时错误,而该代码在我的计算机上使用各种测试输入运行良好。我还牢记中给出的约束问题,但我仍然无法调试它。这道题不是来自任何比赛,而是一道练习题。请指出您能发现的任何错误。 Actual codechef question

#include<stdio.h>

int cash[101][101]={0};
int rec[101][2];
int ri=0;
int sumx(int mat[101][101],int i,int j,int lines)
{
int n=0,a=0,b=0;
if(cash[i][j]!=0)
{
return cash[i][j];
}
else if(i==lines-2)
{
n=(mat[i+1][j]>mat[i+1][j+1])?mat[i+1][j]:mat[i+1][j+1];
cash[i][j]=n+mat[i][j];
rec[ri][0]=i;
rec[ri++][1]=j;
return n+mat[i][j];
}
else
{
a=sumx(mat,i+1,j,lines);
b=sumx(mat,i+1,j+1,lines);
n=(a>b)?a:b;
cash[i][j]=n+mat[i][j];
rec[ri][0]=i;
rec[ri++][1]=j;
return n+mat[i][j];
}
}

int main()
{
int i=0,k=0;
int lines=0,n=0;
int r=0;
int tc=0;
int mat[101][101];
scanf("%d",&tc);
while(tc--)
{
scanf("%d",&lines);
i=0;
k=0;
while(i<lines)
{
while(k<=i)
{
scanf("%d",&mat[i][k]);
k++;
}
k=0;
i++;
}
if(lines==1)
{
r=mat[0][0];
}
else
{
r=sumx(mat,0,0,lines);
}
i=0;
while(i<ri)
{
cash[(rec[i][0])][(rec[i][1])]=0;
rec[i][0]=0;
rec[i][1]=0;
i++;
}
ri=0;
printf("%d\n",r);
}
return 0;
}

最佳答案

错误在于行

while(i<ri)
{
cash[(rec[i][0])][(rec[i][1])]=0;
rec[i][0]=0;
rec[i][1]=0;
i++;
}

rec[i][0] rec[i][1] 的值在某些情况下可以是未定义的,即它们可能返回垃圾值

您可以改用 memset 将值更改为 0

memset(rec,0,sizeof(rec));
memset(cash,0,sizeof(cash));

我运行了你的解决方案,你的算法实现中有一个错误尝试自己找到它

我可以为您提供一个失败的测试用例(使用测试用例生成器)

21
79
89 28
14 6 63
96 58 67 48
80 8 22 27 8
24 21 23 96 97 72
38 90 95 83 57 60 94
13 96 9 24 65 27 67 40
26 20 58 42 29 8 52 49 37
80 65 65 34 79 10 89 11 20 84
57 59 72 79 51 67 84 70 43 62 96
16 4 18 9 5 40 34 2 15 4 28 50
29 1 60 39 28 92 38 65 95 57 10 71 37
25 78 96 43 17 51 88 19 0 30 20 80 39 35
55 41 63 76 4 20 97 72 43 93 76 11 82 33 25
61 85 41 77 42 90 20 5 69 51 4 54 41 18 83 72
12 56 21 82 7 1 84 26 47 26 22 52 84 39 75 70 89
12 39 83 92 49 20 35 20 31 96 66 75 48 79 13 51 49 50
42 81 0 58 70 40 16 83 27 34 79 64 14 26 19 22 38 55 93
64 81 26 29 47 22 73 61 3 2 61 99 18 43 33 10 13 46 24 53
5 56 0 0 3 0 71 12 82 34 17 11 14 51 1 82 73 53 85 75 89

正确答案是 1431 而你的代码返回 1299

关于c - codechef 练习题中的运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24529984/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com