question statement -- find whether a graph is a tree or not .. or check graph contain any cycle or not.
#######################editorial################################################
we can check this by using recursive dfs.
if any node is currently in the recursion stack and from some node it is trying to visit again than it must form cycle.
recursion stack - recursion stack contain those vertices which are currently in recursion since some child of that node is still remain to visit .
ex--
if node a is connected with node b and node c than in recursive dfs once b is found to a it call dfs with b
node c which is connected with a still remain to visit so node a is in recursion stack so that after completion of dfs by node b it start dfs with c(which is also connected with a )..
for this problem we maintain a hashing array res_stack[] whic contain which node is present in recursion stack or which is not..
note--
parent node alwese present in recursion stack so in case of undirected graph for parrent node it not form cycle . so take special care for parent node ..
###################### problems######################################
http://www.spoj.com/problems/PT07Y/############################### code ######################################
#include<iostream>
using namespace std;
#include<bits/stdc++.h>
int visited[100001];
list<int> li[10001];
int rec_stack[1000001];
int par[100001];
int dfs(int start)
{
list<int>:: iterator it;
for(it=li[start].begin();it!=li[start].end();it++)
{
if(visited[*it]==0 )
{
visited[*it]=1;
par[*it]=start;
rec_stack[*it]=1;
dfs(*it);
}
else if(visited[*it]==1 && rec_stack[*it]==1 && par[start]!=*it )
{
if(rec_stack[*it]==1)
return 1;
}
}
rec_stack[start]=1;// now since all node adjecent to node start are covered so remove it // from recursion stack
return 0;
}
int main()
{
int n;
cin>>n;
int m;
cin>>m;
for(int i=0;i<m;i++)
{
int a,b;
cin>>a>>b;
li[a].push_back(b);
li[b].push_back(a);
}
for(int i=1;i<=n;i++)
{
if(visited[i]==0)
{
visited[i]=1;
rec_stack[i]=1;
int k=dfs(i);
if(k==1)
{
cout<<"NO"<<endl;
return 0;
}
}
}
cout<<"YES"<<endl;
return 0;
}
No comments:
Post a Comment