J - A Bug’s Life POJ - 2492(带权并查集)
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!
Hint
Huge input,scanf is recommended.
题意:有n只蜜蜂,异性配对,给出n只蜜蜂的m次配对情况,判断有没有同性恋的。
错误思路:一开始以为直接找回路就好了,结果wa了,原因是,1 3 配对 2 1 配对 那么在并查集中pre[1]=3,pre[2]=1,那么根据压缩路径pre[2] = 3,但实际上2 3 是同性的。
正确思路:带权并查集。0表示同性,1表示异性。详先代码。
代码:
#include <iostream>
#include <stdio.h>
using namespace std;
int pre[20005];
int date[20005]; // 0同行 1异性
int n,m,isp,a,b;
int root(int x) // 压缩路径,维护权值
{
if ( x!=pre[x] ) {
int t = pre[x];
pre[x] = root(pre[x]);
date[x] = ( date[x]+date[t] )%2; // 可以画图辅助推出公式
}
return pre[x];
}
void join(int a, int b)
{
int x = root(a);
int y = root(b);
if ( x==y ) {
if ( (date[a]+date[b])%2==0 ) { // a和b同性
isp = 0;
}
}
else {
pre[x] = y;
date[x] = (date[b]+date[a]+1)%2; // 画图辅助理解
}
}
int main()
{
int listt,i,j;
scanf("%d",&listt);
for ( int ji=1; ji<=listt; ji++ ) {
isp = 1;
scanf("%d %d",&n,&m);
for ( i=1; i<=n; i++ ) {
pre[i] = i;
date[i] = 0;
}
for ( i=0; i<m; i++ ) {
scanf("%d %d",&a,&b);
join(a,b);
}
if ( isp==1 ) {
printf("Scenario #%d:\n",ji);
printf("No suspicious bugs found!\n");
}
else {
printf("Scenario #%d:\n",ji);
printf("Suspicious bugs found!\n");
}
printf("\n");
}
return 0;
}