我一直在 SPOJ 上尝试这个问题.
我一直遇到运行时错误 (SIGSEGV),但代码在我的计算机上运行完美,有人可以告诉我我的错误是什么吗?
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node * next;
int x;
};
int main()
{
struct node *head,*temp,*temp2;
int i,a[400],top=2;
a[0]=2;a[1]=3;
head=(struct node*) malloc(sizeof(struct node));
head->x=5;
head->next=NULL;
temp=head;
for(i=7;i<3000;i++)
{
if(i%3!=0)
{
temp->next=(struct node*) malloc(sizeof(struct node));
temp=temp->next;
temp->x=i;
temp->next=NULL;
}
i++;
}
temp=head;
while(head!=NULL)
{
temp=head;
while(temp!=NULL)
{
for(i=1;i<head->x;i++)
{
if(temp==NULL)
{break;}
else
temp=temp->next;
}
if(temp!=NULL)
{
temp2=temp->next;
if(temp2!=NULL)
{
temp->next=temp->next->next;
free(temp2);
}
}
}
a[top]=head->x;
top++;
temp2=head;
head=head->next;
free(temp2);
}
while(1)
{
scanf("%d",&i );
if(i!=0)
printf("%d\n",a[i-1]);
else
break;
}
return 0;
}
最佳答案
你的数组维度是错误的。来自contest page :
Input Specification
The input contains several test cases. Each test case consists of an integer
n
. You may assume that1<=n<=3000
. A zero follows the input for the last test case.Output Specification
For each test case specified by
n
output on a single line then
-th lucky number.
n
是幸运数字的索引。这意味着你的数组 a
, 必须能够保存至少 3001 个值。您已将其标注为 400,但未检查 top
溢出。当 SPOJ 的测试套件使用大于 400 的值对其进行测试时,您会得到未定义的行为并且很可能会崩溃。
您必须在第一个循环中向列表中添加多少项?尝试一些数字,看看何时溢出 top
(你应该检查一下,即使数组现在足够大了。)然后检查 a[3001]
的值。并在第一个循环中使用该值或稍高的值。
你递增 i
在那个循环中两次,这是故意的,但令人困惑。考虑通过在每一步中递增 2 来使意图更清晰:
for (i = 7; i < 33900; i +=2)
关于c - 段错误spoj协助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30328580/