题意: 有个很大的网络发展,现在有n个独立的结点。输入一串命令,如果是E u 就查询u到他的根结点的距离,如果是I u v,就让v做u的父节点,距离为u-v的绝对值模1000。
分析:并查集问题,比较简单,在find函数记录a【x】的累加。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
int a[20005];
int per[20005];
int n;
void init(int n)
{
for(int i = 1; i <= n; i++)
{
per[i] = i;
}
}
int find(int x)
{
if(x == per[x]) return x;
int m = find(per[x]);
a[x] += a[per[x]];
per[x] = m;
return m;
}
int main()
{
int t; cin >> t;
while(t--)
{
memset(a, 0, sizeof(a));
cin >> n;
init(n);
char c;
while(cin >> c && c != '0')
{
if(c == 'E'){
int m; cin >> m;
find(m);
cout << a[m] << endl;
}
if(c == 'I'){
int x, y, p; cin >> x >> y;
if(x > y) p = x-y;
else p = y-x;
per[x] = y;
a[x] += p%1000;
}
}
}
return 0;
}