您的位置:首页 > 其它

luogu1196 [noi2002]galaxy银河英雄传说(带权并查集)

2017-09-05 14:50 274 查看
挺裸的带权并查集。。。注意一下N应该是300000,而不是30000

#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
int const N=300005;
int n,fa
,size
,s
;//s[i] i前面有多少战舰
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
return x*f;
}
inline int find(int x){
if(fa[x]==x) return x;
int xx=find(fa[x]);
s[x]+=s[fa[x]];
return fa[x]=xx;
}
int main(){
//  freopen("a.in","r",stdin);
n=read();
for(int i=1;i<=n;++i) fa[i]=i,size[i]=1;
while(n--){
char ss[2];scanf("%s",ss);
int x=read(),y=read();
int xx=find(x),yy=find(y);
if(ss[0]=='M'){
fa[xx]=yy;s[xx]=size[yy];size[yy]+=size[xx];
}
if(ss[0]=='C'){
if(xx==yy) printf("%d\n",abs(s[x]-s[y])-1);
else puts("-1");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: