poj 2492 A Bug's Life

Time Limit: 10000MS Memory Limit: 65536K
Total Submissions: 13804 Accepted: 4431

本题的思想就是并查集,分别查找交配双方的根节点,如果根节点相同则证明是同性恋,如果根节点不同,就将对方加入到与自己相对的那个集合里面。

注意:当找到同性恋是并不能直接跳出循环,应该等所有的数据都输入完以后,为了节约时间可以用continue;但是一定要保证所有的数据都输入进去

代码:

 

  
    
1 #include < stdio.h >
2   int o[ 2005 ],rank[ 2005 ],father[ 2005 ];
3   int find( int x)
4 {
5 if (x != father[x])
6 father[x] = find(father[x]);
7 return father[x];
8 }
9   void Union( int x, int y)
10 {
11 if (x == y)
12 return ;
13 if (rank[x] > rank[y])
14 {
15 father[y] = x;
16 }
17 else
18 {
19 if (rank[x] == rank[y])
20 {
21 rank[y] ++ ;
22 }
23 father[x] = y;
24 }
25 }
26
27   int main()
28 {
29 int n,b,t,i,mark,f,ff,x,y,f1, ff1, count = 0 ;
30 scanf( " %d " , & n);
31 while (n -- )
32 {
33 count ++ ;
34 mark = 0 ;
35 scanf( " %d%d " , & b, & t);
36 for (i = 1 ;i <= b;i ++ )
37 {
38 rank[i] = 0 ;
39 father[i] = i;
40 o[i] = 0 ;
41 }
42 for (i = 1 ;i <= t;i ++ )
43 {
44 scanf( " %d%d " , & x, & y);
45 if (mark)
46 continue ;
47 f = find(x);
48 ff = find(y);
49 if (f == ff)
50 mark = 1 ;
51 else
52 {
53 if (o[x] != 0 )
54 {
55 f1 = find(o[x]); // 错了几次在这里,本来想省一个变量,却变成悲剧!
56 Union(f1,ff);
57 }
58 if (o[y] != 0 )
59 {
60 ff1 = find(o[y]);
61 Union(f,ff1);
62 }
63 }
64 o[x] = y;
65 o[y] = x;
66 }
67 printf( " Scenario #%d:\n " ,count);
68 if (mark)
69 printf( " Suspicious bugs found!\n " );
70 else
71 printf( " No suspicious bugs found!\n " );
72 printf( " \n " );
73 }
74 return 0 ;
75 }
76
77
78

 

 

 

你可能感兴趣的:(life)