题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1272
题目大意:
给一个无向图,判断是不是有环,有就输出No,否则输出Yes
题目思路:
用并查集,开始还天真地以为要用拓扑排序,好吧……虽然那个也可以做,可是为什么不用简单的方法呢?
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <cctype> 6 #include <stack> 7 #include <queue> 8 #include <deque> 9 #include <map> 10 #include <set> 11 #include <vector> 12 #include <cmath> 13 #include <algorithm> 14 #define lson l, m, rt<<1 15 #define rson m+1, r, rt<<1|1 16 using namespace std; 17 typedef long long int LL; 18 const int MAXN = 0x7fffffff; 19 const int MINN = -0x7fffffff; 20 const double eps = 1e-9; 21 const int dir[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{-1,1}, 22 {1,1},{1,-1},{-1,-1}}; 23 const int MAX = 100000+10; 24 int parent[MAX]; 25 bool flag; 26 void init() { 27 for (int i = 1; i<=MAX; ++i) parent[i] = -1; 28 } 29 int find(int x) { 30 int s; 31 for (s = x; parent[s] != s; s = parent[s]) ; 32 while (s != x) { 33 int tmp = parent[x]; parent[x] = s; x = tmp; 34 } 35 return s; 36 } 37 void Union(int R1, int R2) { 38 int r1 = find(R1), r2 = find(R2); 39 if (r1 != r2) parent[r1] = r2; 40 else flag = false; 41 } 42 int main(void){ 43 #ifndef ONLINE_JUDGE 44 freopen("hdu1272.in", "r", stdin); 45 #endif 46 int a, b; bool re = true; 47 map<int, bool> mymap; 48 while (1) { 49 init(); flag = true; 50 mymap.clear(); 51 while (~scanf("%d%d", &a, &b)) { 52 if (a == 0 && b == 0) break; 53 if (!mymap[a]) {parent[a] = a;mymap[a] = true;} 54 if (!mymap[b]) {parent[b] = b;mymap[b] = true;} 55 if (a == -1 && b == -1) {re = false; break;} 56 Union(a, b); 57 } 58 if (!re) break; 59 int cnt = 0; 60 for (int i = 1; i < MAX; ++i) { 61 if (mymap[i] && parent[i] == i) { 62 cnt++; 63 } 64 } 65 if (cnt > 1) flag = false; 66 if (flag) printf("Yes\n"); else printf("No\n"); 67 } 68 69 return 0; 70 }
代码比较挫……也比较乱。。这题目就是输入的时候需要处理一下,别的没什么。