洛谷 #1196. 银河英雄传说

版权声明:转载请注明出处 https://blog.csdn.net/qq_41593522/article/details/83993720

题意

n条链,可以将一条链连到另一条链的尾部,查询两个点之间的距离

题解

带权并查集(几乎是模板吧)

调试记录

getf的时候,要先把f[x]的dis更新

#include <cstdio>
#define maxn 30005
using namespace std;
int _abs(int x){return x > 0 ? x : -x;}
int f[maxn], dis[maxn], size[maxn];
int getf(int x){
	if (f[x] == x) return x;
	getf(f[x]);
	dis[x] += dis[f[x]];
	return f[x] = getf(f[x]);
}
void Union(int x, int y){
	int ux = getf(x), uy = getf(y);
	dis[ux] += size[uy];
	size[uy] += size[ux];
	size[ux] = 0;
	f[ux] = uy;
}
int T, n = 30000;
int main(){
	scanf("%d", &T);
	for (int i = 1; i <= n; i++) f[i] = i, dis[i] = 0, size[i] = 1;
	while (T--){
		char opt[5]; int x, y;
		scanf("%s%d%d", opt, &x, &y);
		if (opt[0] == 'M') Union(x, y);
		if (opt[0] == 'C'){
			if (getf(x) != getf(y)) puts("-1");
			else printf("%d\n", _abs(dis[x] - dis[y]) - 1);
		}
	} 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41593522/article/details/83993720