原文地址:A Bug's Life -Poj
作者:兰多夫87
A Bug's Life
Time Limit: 10000MS Memory Limit: 65536K
Total Submissions: 25599 Accepted: 8332
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!
Hint
Huge input,scanf is recommended.
Source
TUD Programming Contest 2005, Darmstadt, Germany
主要算法:并查集
我们用f[i]表示i的父亲,用v[i]表示i与他父亲的关系,0表示同性,1表示异性
首先我们初始化,f[i]=i;v[i]=0;
每次给出两只虫子,我们先判断他们的祖先是否相同,如果相同,那他们的关系我们是已知的,可以通过他们与祖先的关系推出,再判断是否矛盾
如果不相同,就把它们的祖先的关系推出来,再把他们的祖先建立关系
注意路径压缩时,v[x]一起更新,不要弄错了
代码:
const
maxn=2000;
var
f,v:array[0..maxn]of longint;
t,i:longint;
function find(x:longint):longint;
var
k:longint;
begin
if f[x]=x then exit(x);
k:=f[x];
f[x]:=find(f[x]);
v[x]:=(v[x]+v[k])and 1;
exit(f[x]);
end;
procedure work;
var
n,m,i,j,k,x,y:longint;
begin
fillchar(f,sizeof(f),0);
fillchar(v,sizeof(v),0);
readln(n,m);
for i:=1 to n do
f[i]:=i;
for i:=1 to m do
begin
readln(x,y);
if find(x)=find(y) then
if (v[x]+v[y])and 1<>1 then
begin
writeln('Suspicious bugs found!');
for j:=i+1 to m do
readln;
exit;
end;
k:=v[x];
x:=f[x];
f[x]:=f[y];
v[x]:=((k+v[y])+1)and 1;
end;
writeln('No suspicious bugs found!');
end;
begin
readln(t);
for i:=1 to t do
begin
writeln('Scenario #',i,':');
work;
writeln;
end;
end.