GRAPH problem | WHY NOT giving correct answer on test case 3

Revision en3, by GreedyXploit, 2020-09-13 11:36:12
#include<bits/stdc++.h>
using namespace std;
int ct = 0;int ans = 0;
vector<int> a[5000+1];
bool checked[5000+1] = {false};

void dfs(int u )
{
    if(checked[u])
    {
       // cout<<u<<"\n";
        ans++;
        return;
    }
    //cout<<ans<<"\n";
    checked[u] = true;

    for(int i = 0 ; i<a[u].size() ; i++)
    {
        dfs(a[u][i]);
    }

}
int main()
{
    int n ;
    cin>>n;
    for(int i = 1 ; i<n;i++ )
    {
        int k ; 
        cin>>k;
        a[i].push_back(k);

    }
    
    dfs(1);
    //for(int i = 0 ; i<5 ; i++)
    //cout<<checked[i]<<"\n";   
    if(ans > 0)
    cout<<"YES";
    else
    cout<<"NO";
}

QUESTION LINK

THE TEST CASE IN WHICH I FAIL

test case 3 : 3 3 1 2

Tags #graph theory, #dfs

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English GreedyXploit 2020-09-13 11:36:12 8 Tiny change: '}\n~~~~~\n![ QUESTION LINK HERE ](https://' -> '}\n~~~~~\n[QUESTION LINK](https://'
en2 English GreedyXploit 2020-09-13 11:35:09 2 Tiny change: 'i++)\n cout<<chec' -> 'i++)\n //cout<<chec'
en1 English GreedyXploit 2020-09-13 11:33:49 888 Initial revision (published)