Trying to solve SPOJ problem Is it a tree?
Based this on this tutorial
But I am always getting NO as on output. Please help where am I going wrong?
#include<iostream>
#include<cmath>
#include<vector>
#include<climits>
#include<algorithm>
#include<list>
using namespace std;
class graph
{
public:
long v;
bool cyc();
bool dfs(long v,bool visited[],long parent);
void addedge(long v,long w);
graph(long v);
list<long> *adj;
};
graph::graph(long v)
{
this->v = v;
adj = new list<long>[v];
}
void graph::addedge(long v,long w)
{
adj[v].push_back(w);
adj[w].push_back(v);
}
bool graph::dfs(long v,bool visited[],long parent)
{
visited[v] = true;
//cout<<v<<" ";
list<long>::iterator i;
for(i=adj[v].begin();i!=adj[v].end();++i)
{
if(!visited[*i])
{
if (dfs(*i,visited,v))
return true;
}
else if(*i!=parent)
{
return true;
}
}
return false;
}
bool graph::cyc()
{
bool *visited = new bool[v];
long i;
for(i=0;i<v;i++)
{
visited[i] =false;
}
for(i=0;i<v;i++)
if(!visited[i])
if (dfs(i,visited,-1))
return true;
else
return false;
return false;
}
int main()
{
long m,n,v,w;
cin>>n>>m;
graph g(n);
for(long i=0;i<m;i++)
{
cin>>v>>w;
g.addedge(v-1,w-1);
g.addedge(w-1,v-1);
}
if(m!=n-1)
{
cout<<"NO"<<endl;
return 0;
}
if(g.cyc())
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}