" Topic link " click here~~
" topic " Given many pairs of nodes, determine whether all nodes can form a tree
" problem-solving ideas " and check the basic operation of the set, define Node,edge, count the number of node and edge, if (edge==node-1| | Node==0) can become a tree
Tree decision: N nodes, up to n-1, only one into the edge, not 0 points, the other degree is not more than 1, but pay attention to POJ data if 1 1 0 0 will not meet the requirements, that is, can not point to their own
Code:
/*AUTHOR:HRW Tree Decision: N nodes, up to n-1 edge not ring only a point of 0 points other than 1*///#include <bits/stdc++.h> #include <stdio.h># Include <string.h> #include <algorithm> #include <iostream>using namespace Std;const int N=100005;int Father[n],sum[n],a,b,node,edge,vis[n],flag;int find (int x) {if (x==father[x]) return x; return Father[x]=find (father[x ]); }void Union (int a,int b) {if (!vis[a]) node++,vis[a]=true; if (!vis[b]) node++,vis[b]=true; int Pa=find (a); int Pb=find (b); if (PA!=PB) {FATHER[PA]=PB; edge++; } else flag=true;} void Init () {node=edge=0; Flag=false; memset (vis,false,sizeof (VIS)); for (int i=1; i<n; i++) father[i]=i;//father Array initialization}int main () {int a,b,tot=1; Init (); while (scanf ("%d%d", &a,&b) &&a!=-1&&b!=-1) {if (a==0&&b==0) {printf (' Case% D%s\n ", tot++, (!flag&& (edge==node-1| | node==0))? " is a tree. ":" was not a tree. "); Init (); Continue } Union (A, b); } return 0;}
POJ 1308 is It A Tree? && Nyoj 129 (Tree decision + and check set)