您的位置:首页 > Web前端

POJ-2492 A Bug's Life 并查集

2014-04-13 16:47 495 查看
题目链接

POJ1182 1703 类型

题目大意:给出N条虫子,然后a和b交配,给出M对a和b后问

有没有同性恋的虫子

#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<math.h>
#include<functional>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 1000005;
const int inf = 1<<29;
int n,m;
int p[maxn],sex[maxn];  //g 0表示相同 1表示不同

int find( int x )
{
if( p[x] == x )	return x;
int tmp = p[x];
p[x] = find(p[x]);
sex[x] = (sex[x]+sex[tmp])%2;
return p[x];
}
void merge( int x,int y )
{
int fx = find(x);
int fy = find(y);
p[fy] = fx;
sex[fy] = ( sex[y] + sex[x] + 1 )%2;
}
void init()
{
for( int i = 0; i <= n; i ++ ){
p[i] = i;
sex[i] = 0;
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("data.txt","r",stdin);
#endif
char ch;
int cas,x,y;
scanf("%d",&cas);
for( int cs = 1; cs <= cas; cs ++  ){
int flag = 0;
scanf("%d%d",&n,&m);
init();
for( int i = 0; i < m; i ++ ){
scanf("%d%d",&x,&y);
if( find(x) == find(y) ){
if( sex[x] == sex[y] )
flag = 1;
}
else{
merge( x,y );
}
}
printf("Scenario #%d:\n",cs);
if( flag )
puts("Suspicious bugs found!");
else
puts("No suspicious bugs found!");
puts("");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: