您的位置:首页 > 其它

【CDOJ 1328】卿学姐与诡异村庄 【并查集】

2016-07-30 10:44 267 查看
http://acm.uestc.edu.cn/#/problem/show/1328

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
#include<set>
using namespace std;
#define T 100000+50
#define inf 0x3f3f3f3f
typedef long long ll;

int f[T<<1];

void Init()
{
for(int i=0;i<T;++i){
f[i] = i;
}
}

int find(int x)
{
int tmp = x;
while(x!=f[x])
{
x = f[x];
}
while(tmp!=x)
{
int t = f[tmp];
f[tmp] = x;
tmp = t;
}
return x;
}

int main()
{
#ifdef zsc
freopen("input.txt","r",stdin);
#endif

int n,m,i,j,k;
while(~scanf("%d",&n))
{
Init();
int u,v;
for(i=1;i<=n;++i){
scanf("%d%d",&u,&v);
if(v==1){
int tx = find(u*2-1),ty=find(i*2-1);
if(tx!=ty){
f[tx] = ty;
}
tx = find(u*2),ty = find(i*2);
if(tx!=ty){
f[tx] = ty;
}
}
else {
int tx = find(u*2),ty=find(i*2-1);
if(tx!=ty){
f[tx] = ty;
}
tx = find(u*2-1),ty = find(i*2);
if(tx!=ty){
f[tx] = ty;
}
}
}
bool flag = false;
for(i=1;i<=n;++i)if(find(i*2)==find(i*2-1)){flag = true;break;}
if(flag)printf("One face meng bi\n");
else printf("Time to show my power\n");
}
return 0;
}


or

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
#include <stack>
#include <map>
#include <vector>
#include <cstdlib>
#include <string>

#define PI acos((double)-1)
#define E exp(double(1))
using namespace std;
const int has=1e5;
int root[2*has+10];
int fd(int x)
{
return x!=root[x]?root[x]=fd(root[x]):x;
}
void join(int x,int y)
{
int a=fd(x),b=fd(y);
if(a!=b)root[a]=b;
}
int main (void)
{
int n;
cin>>n;
for(int i=1;i<=has*2+9;i++)
root[i]=i;
for(int i=1;i<=n;i++)
{
int x,op;
scanf("%d%d",&x,&op);
if(op==1)
join(i,x),join(has+i,has+x);
else
join(i,has+x),join(has+i,x);

}
for(int j=1;j<=n;j++)
if(fd(j)==fd(has+j))
{
printf("One face meng bi\n");return 0;
}
printf("Time to show my power\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  并查集