HDU 1829 A Bug's Life(並查集)
問題描述:
Problem Description
Background
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
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!
大致題意:
現在有n個果蠅,m個關係。
3 3
1 2
2 3
1 3
比如說這組樣例。3個果蠅,3個關係。
1和2性別不同,2和3性別不同,1和3性別不同。
問這些關係有沒有矛盾。
思路分析:
我們構造一個(a1+n)號果蠅和a1果蠅性別相反。
那麼輸入的a1,a2.
a1就和a2+n性別相同,a2和a1+n相同。
再通過並查集就可以查出有沒有矛盾。
ac程式碼:
#include<bits/stdc++.h>
using namespace std;
int a[30005];
int GetParent(int i)
{
if(a[i]!=i)
a[i]=GetParent(a[i]);
return a[i];
}
void Merge(int i,int j)
{
int p1,p2;
p1=GetParent(i);
p2=GetParent(j);
if(p1==p2)
return ;
a[p2]=p1;
}
int main()
{
int T,n,m;
int i,j,k;
int a1,a2;
int flag;
cin>>T;
int top=0;
while(T--)
{
cout<<"Scenario #"<<++top<<":"<<endl;
flag=0;
cin>>n>>m;
for(i=0;i<=2*n;i++)
a[i]=i;
for(i=0;i<m;i++)
{
cin>>a1>>a2;
if(flag)
continue;
if(GetParent(a1)==GetParent(a2))
{
flag=1;
continue;
}
//cout<<GetParent(a1)<<" "<<GetParent(a2)<<endl;
Merge(a1,a2+n);
Merge(a1+n,a2);
}
if(flag)
cout<<"Suspicious bugs found!"<<endl<<endl;
else
cout<<"No suspicious bugs found!"<<endl<<endl;
}
}