http://poj.org/problem?id=1962
题意:给你1-n个点,E x操作代表查询x到根节点的距离,I x y操作代表将x的父节点置为y。
思路:和poj1962有点像,两道题都比较生动ahhh。。值得注意的一点是合并操作时由于计算的是x到根节点的距离,所以直接改变x的父节点以便同步。
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 100010;
const int INF = 0x3f3f3f3f;
int pre[N], dis[N], n;
int Find(int x)
{
if(x == pre[x]) return x;
int tmp = pre[x];
pre[x] = Find(pre[x]);
dis[x] += dis[tmp];
return pre[x];
}
void Union(int x, int y)
{
int rx = Find(x);
int ry = Find(y);
pre[x] = ry;
dis[x] = abs(x-y)%1000+dis[y];
}
void init()
{
memset(dis, 0, sizeof(dis));
for(int i = 1; i <= n; i++)
pre[i] = i;
}
int main()
{
// freopen("in.txt", "r", stdin);
int t, x, y;
char s[5];
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
init();
while(scanf("%s", s))
{
if(s[0] == 'O') break;
else if(s[0] == 'E')
{
scanf("%d", &x);
Find(x);
printf("%d\n", dis[x]);
}
else if(s[0] == 'I')
{
scanf("%d%d", &x, &y);
Union(x, y);
}
}
}
return 0;
}