Can someone find the error in this code?It is able to pass all the given test cases but submission is not accepted.

#include<bits/stdc++.h>
#include
using namespace std;
int main()
{
int n;
vector v;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int h[1000]={};
int m=0;
for(int j=0;j<n;j++)
{
int k=j;
while(h[a[k]]==0)
{
h[a[k]]=1;
v.push_back(k+1);
k=a[k]-1;
if(h[a[k]]==1)
{
m++;
v.push_back(k+1);
v.push_back(-1);
}
}
}
cout<<m<<endl;
for(int p=0;p<v.size();p++)
{
if((v.at(p))!=-1)
cout<<v.at(p)<<" ";
else
cout<<endl;

}

}

here is the link to the code:
https://www.codechef.com/viewsolution/18620745

here is the link to question:

C++ stores garbage values once you declare “int h[1000]”. You need to initialise the values yourself. Otherwise, your solution is perfectly OK!!

Corrected solution: CodeChef: Practical coding for everyone

This problem is easy, the complexity is O(n^2). This is my solution which gave AC Verdict. Here is the link to my Solution

Please format the question correctly, include the problem link and your submitted solution link.

Thanks for seeing the problem.But the actual problem was not with the re initialization which was correctly done using int h[1000]={};(which automatically initializes the elements of h[1000] array to 0).I should have taken the size of the h[1000] array to be at least h[1001] since value 1000 is also included in the input.Thanks for pointing the error.

Thanks for help.

Oh, sorry… I didn’t know that. Glad to know that it has been solved. :slight_smile: