题目来源:http://poj.org/problem?id=2492
题目分类:并查集
此题心得:学用并查集的关系判断
时间:2011-7-21
A Bug's Life
Description Background Input The first line of the input contains the number of scenarios. Each scenario starts with one line giving the number of bugs (at least one, and up to 2000) and the number of interactions (up to 1000000) separated by a single space. In the following lines, each interaction is given in the form of two distinct bug numbers separated by a single space. Bugs are numbered consecutively starting from one. Output The output for every scenario is a line containing "Scenario #i:", where i is the number of the scenario starting at 1, followed by one line saying either "No suspicious bugs found!" if the experiment is consistent with his assumption about the bugs' sexual behavior, or "Suspicious bugs found!" if Professor Hopper's assumption is definitely wrong. Sample Input 2 3 3 1 2 2 3 1 3 4 2 1 2 3 4 Sample Output Scenario #1: Suspicious bugs found! Scenario #2: No suspicious bugs found! Hint Huge input,scanf is recommended. Source TUD Programming Contest 2005, Darmstadt, Germany |
[Submit] [Go Back] [Status] [Discuss]
All Rights Reserved 2003-2011 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator
题意与分析
题意:题目告诉你人的个数,告诉你m个两两相恋的关系,问这个关系网出来之后会不会有同性恋出现(总所周知只有两种性别)。
分析:简单的并查集只能处理集合的合并,而现在这个题目似乎是要解决集合的拆散。。。也就是说是要维护一种关系状态。因为只有两种性别,所以要充分利用好对2取模。也就是要重新开一个数组来存某个节点和根节点的关系,然后通过与根节点的关系就可以来判断两两之间的关系了。。。
源代码
· //pku 2492
· #include<iostream>
· using namespace std;
·
· const int N=100010;
· int a[N], f[N], r[N], n, m, flag;
·
· int findf(int x)
· {
· if(f[x]!=x)
· {
· int temp = f[x];
· f[x] = findf(f[x]);
· r[x] = (r[x]+r[temp])%2;
· }
· return f[x];
· }
·
· void unionf(int x, int y)
· {
· int fx = findf(x);
· int fy = findf(y);
· if(fx==fy)
· {
· if(r[x]==r[y])
· flag = 0;
· return;
· }
· f[fx] = fy;
· r[fx] = (r[x]+r[y]+1)%2;
· }
·
· int main()
· {
· int i, j, k, cas, cas1=1, x, y;
· scanf("%d", &cas);
· while(cas--)
· {
· scanf("%d%d", &n, &m);
· for(i=1; i<=n; i++)
· {
· f[i] = i;
· r[i] = 0;
· }
· flag = 1;
· while(m--)
· {
· scanf("%d%d", &x, &y);
· unionf(x, y);
· }
· printf("Scenario #%d:\n", cas1++);
· if(flag==0)
· printf("Suspicious bugs found!\n");
· else
· printf("No suspicious bugs found!\n");
· printf("\n");
· }
·
· return 0;
· }