【HDU1325】Is It A Tree?(并查集基础题)
生活随笔
收集整理的這篇文章主要介紹了
【HDU1325】Is It A Tree?(并查集基础题)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
有以下坑點:
1.結(jié)束輸入不一定-1,題目中的敘述只是說所有權(quán)值都為正值。
2.是否構(gòu)成一棵樹不能只判斷是否只有一個根節(jié)點,沒有環(huán)路,而且還需要判斷每個節(jié)點的入度一定是1,不然就不是一棵樹。
(無環(huán)路也可用樹的性質(zhì):結(jié)點數(shù) = 邊樹 + 1 來取代)
?
1 #include <iostream> 2 #include <cstdlib> 3 #include <cstring> 4 #include <cctype> 5 #include <cmath> 6 #include <string> 7 #include <cstdio> 8 #include <algorithm> 9 #include <numeric> 10 using namespace std; 11 12 const int maxn = 25; 13 14 int father[maxn]; 15 int eage[maxn]; 16 bool vis[maxn], flag = 0; 17 int sum = 0; 18 19 int getFather (int x) { 20 while (father[x] != x) { 21 x = father[x]; 22 } 23 return x; 24 } 25 26 void Union (int p, int q) { 27 int x = getFather (p); 28 int y = getFather (q); 29 if (x != y) { 30 father[y] = x; 31 sum ++; 32 } else { 33 flag = 0; 34 } 35 } 36 37 int main () { 38 int x, y, cur = 0; 39 while (cin >> x >> y) { 40 if (x < 0 && y < 0) break; 41 if (x == 0 && y == 0) { 42 printf("Case %d is a tree.\n", ++ cur); 43 continue; 44 } else { 45 flag = 1; 46 memset(vis, 0, sizeof(vis)); 47 memset(eage, 0, sizeof(eage)); 48 for (int i = 0; i < maxn; ++ i) { 49 father[i] = i; 50 } 51 vis[x] = vis[y] = 1; 52 Union(x, y); 53 eage[y] ++; 54 while (cin >> x >> y) { 55 if (x + y == 0) break; 56 vis[x] = vis[y] = 1; 57 Union(x, y); 58 eage[y] ++; 59 } 60 sort(eage, eage + maxn, greater<int>()); 61 int xx = 0; 62 if (eage[0] > 1) flag = 0; 63 for (int i = 1; i < maxn; ++ i) { 64 if (vis[i] && father[i] == i) { 65 xx ++; 66 if (xx > 1) {flag = 0; break;} 67 } 68 } 69 /*for (int i = 1 ; i < maxn; ++ i) { 70 cout << vis[i] << " " ; 71 }*/ 72 73 if (flag) printf("Case %d is a tree.\n", ++ cur); 74 else printf("Case %d is not a tree.\n", ++ cur); 75 } 76 } 77 return 0; 78 }轉(zhuǎn)載于:https://www.cnblogs.com/Destiny-Gem/p/3861247.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的【HDU1325】Is It A Tree?(并查集基础题)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Akka2使用探索2(Con?gurat
- 下一篇: 项目中遇到的ORA error 及解决办