Code for ODD problem DCE05

The program satisfies and gives the right answer for the test cases, But when I submit it gives a runtime error. I know this is not the efficient code for the problem but still I just want to know the error in it

this is the program i submitted for the ODD prob whose link I have mentioned below. It ll be of great help and motivation if I am able to find out the error in this code.

http://www.codechef.com/problems/DCE05

#include<stdio.h>
#define SIZE 100000
int main()
{
int t,a,i,j,c,d;
unsigned long n[SIZE],test,testin[SIZE],testout[SIZE];
scanf("%d",&test);
for(t=0;t<test;t++)
{
scanf("%d",&testin[t]);
for(j=0;j<testin[t];j++)
n[j]=j+1;
path:
    d=0;
    c=2;
for(j=0;j<testin[t];j++)
{
if(n[j]!=0)
{
    if(c%2==0)
    {
        n[j]=0;
    }
c++;
}
}
for(j=0;j<testin[t];j++)
{
    if(n[j]!=0)
        d++;
}
if(d==1)
{
for(i=0;i<testin[t];i++)
{
        if(n[i]!=0)
        testout[t]=n[i];
}
}
else
    goto path;
}
for(t=0;t<test;t++)
    printf("%d\n",testout[t]);
return 0;
}

Hello,

I believe your runtime error is due to excessive memory usage… As you are declaring 3 arrays with size SIZE, which is fine and necessary for this approach, but I believe it might be the cause of your runtime error…

As you pointed out, there’s a much, much more elegant solution to this problem, that uses almost no memory :slight_smile:

Best regards and hope I could help,

Bruno

Hey One more thing…If you want to stick to your naive approach…Plz read…

In C or C++ local var/objects are usually allocated on the stack. You are allocating a large array on the stack, more than the stack can handle,
so you are getting a stackoverflow(I think this is the reason for your RTE).
Don’t allocate it local on stack, use some other place instead. This can be achieved by either making the object global or allocating it on the global heap.
Global variables are fine, if you don’t use the from any other compilation unit. To make sure this doesn’t happen by accident,
add a static storage specifier, otherwise just use the heap.

  1. This will allocate in the BSS segment, which is a part of the heap:

static int c[1000000];
int main()
{
cout << “I love Coding \n”;
return 0;
}

  1. This will allocate in the DATA segment, which is a part of the heap too:

int c[1000000] = {};
int main()
{
cout << “Coding is Fun \n”;
return 0;
}

  1. This will allocate at some unspecified location in the heap:

int main()
{
int* c = new int[1000000];
cout << “Coding is Really Fun \n”;
return 0;
}

So next time you wanna use hell lot of memory use this approach…and remember AdHoc prbs always have some tricks…

Hope it helped…