查环操作,裸题。一次AC。
1 #include <iostream> 2 #include <cstring> 3 #include <cstdlib> 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 maxnn = 1e4 + 10; 13 int cnt = 0, father[maxnn]; 14 15 int getFather (int x) { 16 if (father[x] != x) { 17 father[x] = getFather (father[x]); 18 } 19 return father[x]; 20 } 21 22 void Union (int p, int q) { 23 int x = getFather (p); 24 int y = getFather (q); 25 if (x != y) { 26 father[y] = x; 27 } else { 28 cnt ++; 29 } 30 } 31 32 int main () { 33 int n, x; 34 while (cin >> n >> x) { 35 for (int i = 0; i < x; ++ i) { 36 father[i] = i; 37 } 38 cnt = 0; 39 for (int i = 0 ;i < x; ++ i) { 40 int p, q; scanf("%d%d", &p, &q); 41 Union (p, q); 42 } 43 44 45 /*for (int i = 0; i < n; ++ i) { 46 if (getFather (i) == i) { 47 ans ++; 48 } 49 }*/ 50 cout << cnt << endl; 51 } 52 return 0; 53 }
【HDU2120】Ice_cream's world I(并查集基础题),布布扣,bubuko.com
【HDU2120】Ice_cream's world I(并查集基础题)
原文:http://www.cnblogs.com/Destiny-Gem/p/3861884.html