Uvalive 3027 - Corporative Network(并查集)

题目链接 https://vjudge.net/problem/UVALive-3027


【题意】

    并查集模板题,给定一组序列1-n(n <= 20000),进行若干次操作,E u为查询u的权值,I u v 为设置u为v的父亲结点,且u的权值为|u-v|%1000,对每次的查询操作输出相应结果。


【思路】

    带权并查集的模板题,代码如下:

#include<bits/stdc++.h>
using namespace std;

const int maxn = 20050;

int n;
int par[maxn], dis[maxn];

void init() {
	memset(dis, 0, sizeof(dis));
	for (int i = 1; i <= n; ++i) par[i] = i;
}

int find(int x) {
	if (x == par[x]) return x;
	int pos = find(par[x]);
	dis[x] += dis[par[x]];
	return par[x] = pos;
}

int main() {
	int t;
	char ch[2];
	scanf("%d", &t);
	while (t--) {
		scanf("%d", &n);
		init();
		while (scanf("%s", ch) && ch[0] != 'O') {
			if ('E' == ch[0]) {
				int u;
				scanf("%d", &u);
				find(u);
				printf("%d\n", dis[u]);
			}
			else {
				int u, v;
				scanf("%d%d", &u, &v);
				par[u] = v;
				dis[u] = abs(u - v) % 1000;
			}
		}
	}
	return 0;
}


posted @ 2018-01-06 22:15  不想吃WA的咸鱼  阅读(92)  评论(0编辑  收藏  举报