What is wrong in this logic for 'Chef and Round Run'?

Code :

#include <bits/stdc++.h>
using namespace std;

int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int t,i,n,a[100007],j,k;
cin >> t;
while(t--)
    {
    bool visited[100007]={false};
    set<int> s,b;//s stores all indexes in cycles found till now
    cin >> n;
    for(i=0;i<n;i++)
        {
        cin >> a[i];
        a[i]=(i+a[i]+1)%n;
    }
    for(i=0;i<n;i++)
        {
        if(!visited[i])
            {
            b.clear();//b stores indexes of current cycle check
            j=i;
            while(!visited[j])
                {
                visited[j]=true;
                b.insert(j);
                j=a[j];
            }
            if(b.find(j)!=b.end())//if cycle is found
                {
                if(s.find(j)==s.end())// to check whether cycle currently found has already been found
                    {
                    k=j;
                    s.insert(k);
                    j=a[j];
                    while(k!=j)
                        {
                        s.insert(j);
                        j=a[j];
                    }
                }
            }
        }
    }
    cout << s.size() << endl;
}
return 0;

}

Passing all test cases except the last one. I highly suspect that my code goes into non-terminating loop state. I’ve tried my best to come up with a corner case, but was not able to. Any help would be appreciated.
Thank you :slight_smile:

I have submitted your code, its getting accepted.

https://www.codechef.com/viewsolution/12283820

1 Like

I resubmitted my solution in C++14 just to fail the last test case again. Resubmitted in C++ 4.3.2 which got accepted. Any idea as to why this may have happened? Thanks for the help :slight_smile: