Fork me on GitHub

HDU ACM 1325 / POJ 1308 Is It A Tree?

Is It A Tree?

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6961    Accepted Submission(s): 1619

 

【题目链接】http://acm.hdu.edu.cn/showproblem.php?pid=1325

这题如果用并查集做的话,最后判断的时候还是要看一个结点的入度是否为大于1(纯并查集的情况下),搜了几份代码,有些是去判断是否有环的,这些都不如直接用树的充分条件去判断:一个节点入度为0,其余节点入读为1,V个点只有V-1条边,题目坑你的地方大概有两点:没节点也是树,结束时两个数是负数而不是两个-1

 1 #include <cstdio>
 2 #include <cstring>
 3 #define SIZE 2013
 4 using namespace std;
 5 int father[SIZE];
 6 bool exit[SIZE];
 7 int find(int f)
 8 {
 9     return father[f] = f == father[f] ? f : find(father[f]);
10 }
11 
12 int main()
13 {
14     #ifndef ONLINE_JUDGE
15     freopen("input.txt", "r", stdin);
16     #endif
17     int n, m, T = 0, max = 0, nv = 0, ne = 0;
18     bool flag = true;
19     memset(father, 0, sizeof(father));
20     memset(exit, false, sizeof(exit));
21     while(scanf("%d%d", &n, &m) != EOF)
22     {
23         if(n < 0 && m < 0) break;
24         else if(n+m == 0)
25         {
26             if(ne == 0 && nv == 0)
27             {
28                     printf("Case %d is a tree.\n", ++T);
29                     continue;
30             }
31             if(ne == nv-1)
32             {
33                 int cnt = 0, zero = 0;
34                 for(int i = 0; i <= max; ++i)
35                 if(exit[i])
36                 {
37                     if(!father[i]) zero++;
38                     else if(father[i] == 1) cnt++;
39                 }
40                 if(cnt == ne && zero == 1)
41                     printf("Case %d is a tree.\n", ++T);
42                 else 
43                     printf("Case %d is not a tree.\n", ++T);                
44             }
45             else printf("Case %d is not a tree.\n", ++T);
46             
47             flag = true;            
48             memset(exit, false, sizeof(exit));
49             memset(father, 0, sizeof(father));
50             ne = nv = 0;
51             max = 0;
52         }
53         else 
54         {
55             max = max > n ? (max > m ? max : m) : (n > m ? n : m);
56             if(!exit[n]) 
57             {
58                 exit[n] = true;
59                 nv++;
60             }
61             if(!exit[m])
62             {
63                 exit[m] = true;
64                 nv++;
65             }
66             ne++;
67             father[m]++;
68         }
69     }
70     return 0;
71 }

 

posted @ 2013-07-29 12:54  Gifur  阅读(386)  评论(0编辑  收藏  举报
TOP