[NOI2002]银河英雄传说 边带权并查集

维护两个东西,深度和大小

get操作:

int get(int x){
    if(x==fa[x]) return x;
    int rt=get(fa[x]);
    dep[x]+=dep[fa[x]];
    return fa[x]=rt; 
}

合并(unite)操作:

void unite(int x,int y){
    x=get(x),y=get(y);
    fa[x]=y;
    dep[x]=siz[y];
    siz[y]+=siz[x];
}

根据深度差就能知道两个结点之间有几个点

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 30010;
int fa[N],n,siz[N],dep[N];
void init(){
	for(int i = 1; i <= 30000; i++) fa[i]=i,siz[i]=1;
}
int get(int x){
	if(x==fa[x]) return x;
	int rt=get(fa[x]);
	dep[x]+=dep[fa[x]];
	return fa[x]=rt; 
}
void unite(int x,int y){
	x=get(x),y=get(y);
	fa[x]=y;
	dep[x]=siz[y];
	siz[y]+=siz[x];
}
int main(){
	scanf("%d",&n);
	init();
	char s[3];
	int a,b;
	for(int i = 1; i <= n; i++){
		scanf("%s%d%d",s,&a,&b);
		if(s[0]=='M'){
			unite(a,b);
		}else{
			if(get(a)!=get(b)) puts("-1");
			else{
				printf("%d\n",abs(dep[a]-dep[b])-1);
			}
		}
	}
	return 0;
}
原创文章 85 获赞 103 访问量 2482

猜你喜欢

转载自blog.csdn.net/weixin_43824564/article/details/105880075
今日推荐