hdu--1878--欧拉回路(并查集判断连通,欧拉回路模板题)

 题目链接

 

 1 /*
 2 
 3     模板题-------判断欧拉回路 
 4      
 5     欧拉路径,无向图
 6     1判断是否为连通图, 
 7     2判断奇点的个数为0
 8 */
 9 #include <iostream> 
10 #include <cstring>
11 #include <vector>
12 #include <cstdio>
13 using namespace std;
14 struct DisjoinSet {//并查集判断是否连通
15     vector<int> father, rank;
16     
17     DisjoinSet(int n): father(n), rank(n) {
18         for (int i=0; i<n; i++) {
19             father[i] = i;
20         }
21     }
22     
23     int easy_find(int v)  {//非递归 
24         int k, j, r;
25         r = v;
26         while (r!=father[r]) {
27             r = father[r];
28         }
29         k = v;
30         while (k!=r) {
31             j = father[k];
32             father[k] = r;
33             k = j;
34         }
35         return r;
36     }
37     void merge(int x, int y) {
38         int a = easy_find(x), b = easy_find(y);
39         if (rank[a] < rank[b]) {
40             father[a] = b;
41         } else {
42             father[b] = a;
43             if (rank[b] == rank[a]) {
44                 ++rank[a];
45             }
46         }
47     }
48 } ; 
49 
50 const int MAXN = 1010;
51 int edge[MAXN];
52 int p, q;
53 int main()
54 {
55 //    freopen("in.txt", "r", stdin);
56     while (~scanf("%d %d", &p, &q) && p) {
57         memset(edge, 0, sizeof(edge));
58         DisjoinSet mfs(1010);
59         for (int i=0; i<q; i++) {
60             int a, b;
61             scanf("%d %d", &a, &b);
62             edge[a]++;
63             edge[b]++;
64             mfs.merge(a, b);
65         }
66         int father = mfs.easy_find(1);
67         int ct = 0;
68         for (int i=1; i<=p; i++) {
69             if (mfs.father[i] != father) {
70                 ct = -1;
71                 break;
72             }
73             if (edge[i] & 1) ct++;
74         }
75         if (ct == 0) printf("1\n");//欧拉回路
76         else printf("0\n");
77     }
78     return 0;
79 }

 

posted @ 2018-04-16 14:57  朤尧  阅读(304)  评论(0编辑  收藏  举报