CAPPLE Logic

I don’t understand what’s the difference between

while(t–)
{
int temp;
int count=0;
int n;
int A[100010];
for(int c=0;c<100010;c++)
A[c]=0;
cin>>n;
for(int a=1;a<=n;a++)
{
cin>>temp;
A[temp]++;
}
for(int a=1;a<=n;a++)
{
if(A[a]!=0)
count++;
}
cout<<count<<"\n";
}

and

while(t–)
{
int temp;
int count=0;
int n;
int A[100010];
for(int c=0;c<100010;c++)
A[c]=0;
cin>>n;
for(int a=1;a<=n;a++)
{
cin>>temp;
if(A[temp]==0)
{
A[temp]++;
count++;
}
}
cout<<count<<"\n";
}

because the 1st one is giving a WA for the problem CAPPLE of DEC14, while the 2nd is 100% correct.

Can some one please clear this doubt??

1st code is giving wrong answer because n may me less than the array element ,

suppose n is 5 , and elements are 3 6 100000 3 10
so clearly 100000 is greater than 5 and you are running the loop for(a=1;a<=n;a++) upto n so this will not give correct answer , run this loop upto 100001 to get the correct answer .

1 Like

See this. You are assuming that array elements are in the range 1 to n.

Yeah run the loop upto 100000 to get correct ans. the corrected first code is:

for(int a=1;a<=100000;a++)

nice that you clear your doubts…

Thanks a lot acodebreaker2. It helped!!

Thank you damn_me. The code helped me understand.