poj 2492 并查集

题意:给出N条虫子,然后a和b交配,给出M对a和b后问有没有同性恋的虫子

链接:点我

和黑帮那题差不多

 1 #include <stdio.h>
 2 #include <algorithm>
 3 #include <iostream>
 4 #include <string.h>
 5 using namespace std;
 6 const int MAXN=2010;
 7 int F[MAXN];
 8 int val[MAXN];
 9 int find(int x)
10 {
11     if(F[x]==-1)return x;
12     int tmp=find(F[x]);
13     val[x]+=val[F[x]];
14     val[x]%=2;    //更新子节点的偏移量(即相对根的性别)
15     return F[x]=tmp;
16 }
17 int main()
18 {
19     int T;
20     int n,m;
21     scanf("%d",&T);
22     int iCase=0;
23     while(T--)
24     {
25         iCase++;
26         memset(F,-1,sizeof(F));
27         memset(val,0,sizeof(val));
28         scanf("%d%d",&n,&m);
29         bool flag=true;
30         int u,v;
31         while(m--)
32         {
33             scanf("%d%d",&u,&v);
34             if(!flag)continue;
35             int t1=find(u),t2=find(v);
36             if(t1==t2)
37             {
38                 if(val[u]==val[v])flag=false;
39             }
40             else
41             {
42                 F[t1]=t2;
43                 val[t1]=val[v]-val[u]+1;
44                 val[t1]%=2;    //不属于同一个集合,关键的一步,想了好久,原来是默认性别不同
45             }
46         }
47         if(flag)printf("Scenario #%d:\nNo suspicious bugs found!\n\n",iCase);
48         else printf("Scenario #%d:\nSuspicious bugs found!\n\n",iCase);
49     }
50     return 0;
51 }

 

posted @ 2015-05-06 10:41  miao_a_miao  阅读(120)  评论(0)    收藏  举报