您的位置:首页 > Web前端

poj 2492 A Bug's Life(并查集)

2012-01-21 18:33 507 查看
http://poj.org/problem?id=2492题意:

一个无聊的科学家说只有两个不同性别的BUG能在一起,当然是在没有GAY的情况下。给你几对能在一起的BUG,问里面有没有GAY。

刚拿到这题第一感觉就是并查集,两种关系,把不同性别的BUG放入两个不同集合里。想了一下发现根本不可行

比如1 2\n 3 4的输入,1 2放入两个集合中,3 4又得放两个集合中,明显不行。

既然不能马上确定3 4属于哪个集,能不能先存下来呢?

用一个数组记录下标元素的对立元素

read(x, y) ;

a[x] = y ;

当再次读到此元素时,可直接将与x不同性别的元素合并

read(x, z) ;

Union(z, a[x]) ;

根据这一思路出了如下代码:

#include<cstdio>
#include<cstring>
using namespace std ;
int f[2010] ;
int a[2010] ;
int n, m ;
bool flag ;
void make_Set(){
for(int i=1; i<=n; i++)
f[i] = i ;
}
int find_Set(int x){
if(x!=f[x]){
f[x] = find_Set(f[x]) ;
}
return f[x] ;
}
void Union(int x, int y){
x = find_Set(x) ;
y = find_Set(y) ;
if(x!=y) f[x] = y ;
}
int main(){
int t, ti, i, j, x, y ;
scanf("%d", &t) ;
for(ti=1; ti<=t; ti++){
scanf("%d%d", &n, &m) ;
flag = false ;
memset(a, -1, sizeof(a)) ;
for(i=0; i<=n; i++)
f[i] = i ;
for(i=0; i<m; i++){
scanf("%d%d", &x, &y) ;
if(flag) continue ;
if(a[x]==-1){
if(a[y]!=-1)
Union(x, a[y]) ;
a[x] = y ;
a[y] = x ;
}
else{
if(a[y]==-1){
Union(y, a[x]) ;
a[x] = y ;
a[y] = x ;
}
else{
if(find_Set(x)==find_Set(y)){
flag = true ;
continue ;
}
else{
Union(x, a[y]) ;
Union(y, a[x]) ;
}
}
}
}
if(flag) printf("Scenario #%d:\nSuspicious bugs found!\n\n", ti) ;
else printf("Scenario #%d:\nNo suspicious bugs found!\n\n", ti) ;
}
return 0 ;}

有点投机的感觉...

正统的并查集要怎么做呢?

开辟一个数组来保存x与根节点的关系,r[root]=0, 对于子节点,0表示与根节点同性,反之异性。

这样读入x,y后,只需判断fx是否等于fy,相等再看是否同性,不等则合并。

只用一个集合,借助关系r[]就可确定题解。

这样,关键就在于关系数组r的更新上了。

这里只有两种关系(0, 1)分别代表子节点是否与根节点同性。

1. 在find_Set()中,一定要保证在根节点变动后,子节点关于根节点关系的稳定。 

2. 合并时,fy不再作为根节点,所以其r值决定于x与y的r值。

详情看代码:

#include<cstdio>
using namespace std ;
int f[2010] ;
int r[2010] ;
int n, m ;
bool flag ;
int find_Set(int x){
int temp ;
if(x==f[x]){
return x ;
}
temp = f[x] ;
f[x] = find_Set(temp) ;
r[x] = (r[x]+r[temp]) % 2 ;//保持r[x]相对于根节点的稳定
return f[x] ;
}
void Union(int x, int y, int fx, int fy){
f[fy] = fx ;
r[fy] = (r[x]+r[y]+1) % 2 ;
/*
这里r[fy],r[fx]都为0
r[x]-r[fx] 若x fx同性则为0异性为1
r[y]-r[fy] 若y fy同性则为0异性为1
当x与fx,y与fy都为同性或都为异性时r[fy]的值为1
即(r[x]-r[fx]+r[y]-r[fy]+1)%2
得r[fy] = (r[x]+r[y]+1) % 2 ;
*/
}
int main(){
int t, ti, i, j, x, y, fx, fy ;
scanf("%d", &t) ;
for(ti=1; ti<=t; ti++){
scanf("%d%d", &n, &m) ;
flag = false ;
for(i=0; i<=n; i++){
f[i] = i ;
r[i] = 0 ;
}
for(i=0; i<m; i++){
scanf("%d%d", &x, &y) ;
if(flag) continue ;
fx = find_Set(x) ;
fy = find_Set(y) ;
if(fx==fy){
if(r[x]==r[y]){
flag = true ;
continue ;
}
}
else{
Union(x, y, fx, fy) ;
}
}
if(flag) printf("Scenario #%d:\nSuspicious bugs found!\n\n", ti) ;
else printf("Scenario #%d:\nNo suspicious bugs found!\n\n", ti) ;
}
return 0 ;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: