标签:last NPU def img art iostream tis == with
http://poj.org/problem?id=1308
6 8 5 3 5 2 6 4 5 6 0 0 8 1 7 3 6 2 8 9 7 5 7 4 7 8 7 6 0 0 3 8 6 8 6 4 5 3 5 6 5 2 0 0 -1 -1
Case 1 is a tree. Case 2 is a tree. Case 3 is not a tree.
树应该都很熟悉,简单并查集即可解决此题,做该题主要注意下面几点:
1、判断有没有“环”,即出现“多对一”
2、判断是否有唯一的根结点,即不是多棵树
3、空树也是树
1 #include <stdio.h> 2 #include <string.h> 3 #include <iostream> 4 #include <string> 5 #include <math.h> 6 #include <algorithm> 7 #include <vector> 8 #include <stack> 9 #include <queue> 10 #include <set> 11 #include <map> 12 #include <sstream> 13 const int INF=0x3f3f3f3f; 14 typedef long long LL; 15 const int mod=1e9+7; 16 const int maxn=1e5+10; 17 using namespace std; 18 19 int fa[100010]; 20 vector<int> vt; 21 22 void init(int n) 23 { 24 for(int i=0;i<=n;i++) 25 fa[i]=i; 26 } 27 int Find(int x) 28 { 29 return x==fa[x]? x:fa[x]=Find(fa[x]); 30 } 31 32 int main() 33 { 34 #ifdef DEBUG 35 freopen("sample.txt","r",stdin); 36 #endif 37 // ios_base::sync_with_stdio(false); 38 // cin.tie(NULL); 39 40 int a,b; 41 int flag=1;//判断是否有环,1表示无环 42 init(100005); 43 int T=0;//样例个数 44 while(~scanf("%d %d",&a,&b)&&!(a==-1&&b==-1)) 45 { 46 if(a==0&&b==0)//一个样例结束,判断输出并初始化 47 { 48 int num=0; 49 for(int i=0;i<vt.size();i++) 50 if(vt[i]==fa[vt[i]]) num++; 51 if(flag&&num<=1) printf("Case %d is a tree.\n",++T);//num=0为空树 52 else printf("Case %d is not a tree.\n",++T); 53 flag=1; 54 vt.clear(); 55 init(100005); 56 continue; 57 } 58 int aa=Find(a); 59 int bb=Find(b); 60 if(aa==bb) flag=0;//有环 61 else if(flag)//无环再操作,已经判断有环就不用再进行了 62 { 63 fa[aa]=bb; 64 vt.push_back(a); 65 vt.push_back(b); 66 } 67 } 68 69 return 0; 70 }
-
POJ-1308 Is It A Tree?(并查集判断是否是树)
标签:last NPU def img art iostream tis == with
原文地址:https://www.cnblogs.com/jiamian/p/12258250.html