poj is it a tree ? graph problem .

Revision en4, by MMM24, 2015-06-18 13:23:12

This the problem statement http://poj.org/problem?id=1308 The problem statement give a graph constructed by given each connected nodes and you have to determine if it's a tree or note

first and second are tree and the third is not .

My solution was to find first the root wich should be unique using set otherwise it's not a tree .

while(cin >> a >> b)
{
 graph[a][b]=1;
 s.insert(a);
 if(s.count(b)) s.erase(b);
}

if(s.size()!=1) cout << "Case "<<z<<" is not a tree." << endl ;

once we have found the root i preform a dfs starting from the root .

dfs(root);
void dfs(int x)
{
    visit[x]++;
	if(visitv[x]>2)return;
	int i;
	for(i=0;i<1010;i++)if(graph[x][i])dfs(i);
}

each visited node will be incrimented by 1 . after dfs i check the number of times each node is visited , if it's visited more than one time than the given graph is not a tree otherwise it should be a tree . Any body can tell why this got a WA ? thanks.

Tags graphs, tree

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en4 English MMM24 2015-06-18 13:23:12 59
en3 English MMM24 2015-06-18 13:02:51 0 (published)
en2 English MMM24 2015-06-18 12:56:45 58 (saved to drafts)
en1 English MMM24 2015-06-18 12:55:32 974 Initial revision (published)