poj2492(加權值的並查集)
阿新 • • 發佈:2019-01-23
Description
BackgroundProfessor 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
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.題目意思有點bt,就是正常昆蟲是異性交配,輸入一對就代表這一對交配了,讓你看這一群昆蟲是否有同性戀!
加權值的並查集題目,剛開始會有些不好理解,相當於把有過關係的所有蟲子聯絡在一起,這樣才有可能發現是否是同性戀,而且我們處理這種題目的辦法都是將每個子節點與父節點作比較(這個比方就好比我們確定任何事物的方式一樣,就是先找參照物!!找到參照物了自然關係明瞭),用一個rela陣列來記錄,用0,1來表示與父節點是同性還是異性,那麼自然就好比較兩個昆蟲是否有同性戀情節了。相當於在並查集的原形之上加了一個權值,怎樣記錄權值的變化就成了這題的關鍵!
#include <iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int MAXN = 100010;
int f[MAXN],rela[MAXN];
int ff(int x)
{
int tem=f[x];
if(tem!=x)
f[x]=ff(tem),rela[x]=(rela[x]+rela[tem])%2;
return f[x];
}
void join(int a,int b)
{
int tem1=ff(a),tem2=ff(b);
f[tem1]=tem2;
rela[tem1]=((rela[a]-rela[b]+1)%2);
}
int main()
{
int t,o=1;scanf("%d",&t);
while(t--)
{
int n,m,b,c;
scanf("%d%d",&n,&m);
for(int i=0;i<=MAXN;i++)
f[i]=i,rela[i]=0;
int flag=0;
while(m--)
{
scanf("%d%d",&b,&c);
if(flag==0&&ff(b)!=ff(c))
join(b,c);
else if(flag==0&&ff(b)==ff(c)&&rela[b]==rela[c])
flag=1;
}
if(flag==0)
{
printf("Scenario #%d:\n",o++);
printf("No suspicious bugs found!\n\n");
}else
{
printf("Scenario #%d:\n",o++);
printf("Suspicious bugs found!\n\n");
}
}
return 0;
}