uva 1329

来源:互联网 发布:中信证券网上交易软件 编辑:程序博客网 时间:2024/06/05 05:26

题意:给一个数字n。接下来有一些操作

E a,代表你要输出a到根节点的距离。I a, b。代表把a的父节点设为b。两个节点之间的距离为|a的序号-b的序号| % mod。

参考厚白书:

就是并查集,不过得记录距离。需要注意的是,压缩路径的时候,要注意更新距离,毕竟根节点可能会变化。


#include<cstdio>#include<iostream>#include<algorithm>using namespace std;const int maxn = 20000;const int mod = 1000;struct node{    int f;    int dis;}pa[maxn];int root(int x){    if(x != pa[x].f)    {        int r = root(pa[x].f);//为什么要利用回溯从根节点开始更新距离?因为,本来就应该从根节点开始,开始想错,尴尬。        pa[x].dis += pa[pa[x].f].dis;        return pa[x].f = r;    }    else return pa[x].f;}int main(){    int T;    scanf("%d", &T);    for(int kase = 1; kase <= T; kase++)    {        int n;        scanf("%d", &n);        char cmd;        for(int i = 0; i <= n; i++)        {            pa[i].f = i;            pa[i].dis = 0;        }        while(cin>>cmd && cmd != 'O')        {            if(cmd == 'I')            {                int t1, t2;                scanf("%d%d", &t1, &t2);                pa[t1].dis = abs(t1 - t2) % mod;                pa[t1].f = t2;            }            if(cmd == 'E')            {                int t;                scanf("%d", &t);                root(t);                printf("%d\n", pa[t].dis);            }        }    }    return 0;}