并查集(2)
Description
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.
Input
Output
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!
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int f[2005],y[2005];
void init(int n)
{
for(int i=0;i<n;i++)
f[i]=i;
}
int ff(int x)
{
if(f[x]!=x)
f[x]=ff(f[x]);
return f[x];
}
void join(int a,int b)
{
f[ff(a)]=f[ff(b)];
}
int main()
{
int T,n,m,cas=1;
scanf("%d",&T);
while(T--)
{
int flag=0;
cin>>n>>m;
init(n);
memset(y,0,sizeof(y));
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
if(!(y[a]+y[b]))
{
y[a]=b;
y[b]=a;
}
else if(y[a]&&!y[b])
{
y[b]=a;
join(y[a],b);
}
else if(!y[a]&&y[b])
{
y[a]=b;
join(y[b],a);
}
else
{
join(y[a],b);
join(y[b],a);
}
if(ff(a)==ff(b))
flag=1;
}
printf("Scenario #%d:\n",cas++);
if(flag)
printf("Suspicious bugs found!\n");
else
printf("No suspicious bugs found!\n");
if(T)
printf("\n");
}
return 0;
}
方法二:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int MAX = 2005;
bool flag;
int fa, fb, n;
int father[MAX], rela[MAX];
int find(int x)
{
if(father[x] == -1)
return x;
else
{
int tmp = father[x];
father[x] = find(father[x]);
rela[x] = (rela[x]+rela[tmp])%2;
return father[x];
}
}
int main()
{
int T, m, a, b;
scanf("%d", &T);
while(T--)
{
flag = true;
scanf("%d%d", &n, &m);
memset(father, -1, (n+1)*sizeof(int));
memset(rela, 0, (n+1)*sizeof(int));
while(m--)
{
scanf("%d%d", &a, &b);
if(!flag)
continue;
fa = find(a);
fb = find(b);
if(fa != fb)
{
father[fa] = fb;
rela[fa] = (rela[a] + rela[b] + 1)%2;
}
else
if(rela[a] == rela[b])
flag = false;
}
printf("Scenario #%d:\n", k);
if(flag)
printf("No suspicious bugs found!\n\n");
else
printf("Suspicious bugs found!\n\n");
}
return 0;
}