如题:http://acm.hdu.edu.cn/showproblem.php?pid=1829
A Bug's Life
Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9845 Accepted Submission(s): 3215
Professor Hopper is researching the sexual behavior of a rare species of bugs. He assumes that they feature two different genders and that they only interact with bugs of the opposite gender. In his experiment, individual bugs and their interactions were easy to identify, because numbers were printed on their backs.
Problem
Given a list of bug interactions, decide whether the experiment supports his assumption of two genders with no homosexual bugs or if it contains some bug interactions that falsify it.
2 3 3 1 2 2 3 1 3 4 2 1 2 3 4
Scenario #1: Suspicious bugs found! Scenario #2: No suspicious bugs found!HintHuge input,scanf is recommended.
题目意思很简单,就是给你2个一组放在一起的一堆苍蝇,让你求出是不是有同性恋,比如(1,3),(1,2),(2,3) 1号和2号异性,1号和3号异性,2号和三号肯定是同性。
并查集来维护,网上这一题的解法全都是使用sex[]数组来维护性别的关系,其实还有更方便的方法,只用开一个数组。
开2倍大小,f还是集合,1-N代表的是公,N+1-2*N代表的是母。给出一对苍蝇a,b 如果a,b或a+N,b+N在同一集合,那么就是同性恋,否则合并a,b+N和a+N,b。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define MAX 2005*2
int T,n,m;
int f[MAX];
int rank[MAX];
void init()
{
int i;
for(i=0;i<MAX;i++)
{
f[i]=i;
rank[i]=0;
}
}
int find(int x)
{
if(x==f[x])
return f[x];
else
return f[x]=find(f[x]);
}
int same(int a,int b)
{
return find(a)==find(b);
}
void Union(int a,int b)
{
int fa=find(a);
int fb=find(b);
if(fa==fb)
return;
if(rank[fa]<rank[fb])
f[fa]=fb;
else
{
f[fb]=fa;
if(rank[fa]==rank[fb])
rank[fa]++;
}
}
int main()
{
// freopen("C:\\1.txt","r",stdin);
scanf("%d",&T);
int i;
for(i=1;i<=T;i++)
{
init();
int a,b;
int flag=0;
scanf("%d%d",&n,&m);
while(m--)
{
scanf("%d%d",&a,&b);
if(same(a,b)||same(a+n,b+n))
{
flag=1;
// break; //这里千万不能 break;因为是多组数据,如果打断接下来这一组没结束的输入,开始下一组,就完蛋了。
}
else
{
Union(a,b+n);
Union(a+n,b);
}
}
printf("Scenario #%d:\n",i);
if(flag) printf("Suspicious bugs found!");
else printf("No suspicious bugs found!");
printf("\n\n");
}
return 0;
}