ZOJ 3321题解此题一开始纠结了N久,最后发现原来方法用错了。此题应该用并查集归并判断节点是否相同和所有点度是否为2.

 1 #include<stdio.h>
2 #include<stdlib.h>
3 #define MAX 100
4
5 typedef struct
6 {
7 int a;
8 int b;
9 }Point;
10 Point P[MAX];
11
12 int father[MAX],num[MAX];
13 int Mak_set(int n)
14 {
15 int i;
16 for (i=1; i<=n; i++)
17 {
18 father[i] = i;
19 num[i] = 0;
20 }
21 }
22
23 int Find_set(int x)
24 {
25 if (x != father[x])
26 father[x] = Find_set(father[x]);
27 return father[x];
28 }
29
30 int Union(int x,int y)
31 {
32 x = Find_set(x);
33 y = Find_set(y);
34 if(x != y)
35 father[y] = x;
36 }
37
38 int main()
39 {
40 int i,n, m;
41
42 while(scanf("%d %d", &n,&m) != EOF)
43 {
44 Mak_set(n);
45 for (i=1; i<=m; i++)
46 {
47 scanf("%d %d", &P[i].a,&P[i].b);
48 num[P[i].a]++;
49 num[P[i].b]++;
50 Union(P[i].a,P[i].b);
51 }
52
53 if((n<3) || (n!=m)) /*一开始这个结构放在了最前面总是WA,后来学乖了,调换了一下位置后就AC了*/
54 {
55 printf("NO\n");
56 continue;   /*不能省掉原因我也不是太清楚若有大牛知道请留言指教*/
57 }
58 for (i=1; i<=n; i++)
59 {
60 if ((num[i]!=2) || (father[i]!=father[1]))
61 break;
62 }
63 if (i <=n)
64 printf("NO\n");
65 else
66 printf("YES\n");
67 }
68 return 0;
69 }
70
posted @ 2011-08-17 16:39  zhongya  阅读(231)  评论(0编辑  收藏  举报