1. 程式人生 > >uva 1329 Corporative Network(並查集+路徑壓縮)

uva 1329 Corporative Network(並查集+路徑壓縮)

題目

https://cn.vjudge.net/problem/UVA-1329

路徑壓縮,壓縮同時維護距離,要注意查詢時先find一下,再查詢

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 20005
int father[maxn];
int dis[maxn];
using namespace std;
int find(int x)
{
    if(x==father[x])
    return x;
        int root=find(father[x]);
        dis[x]+=dis[father[x]];
        return father[x]=root;


}
int main()
{
    int t;
    scanf("%d",&t);
    char c;
    while(t--)
    {int n;
    scanf("%d",&n);
    for(int i=0;i<=n;i++)
    {
        father[i]=i;
        dis[i]=0;
    }
    char c;
       while(scanf("%c",&c))
    {if(c=='O')
    break;
     else if(c=='I')
    {
        int u,v;
        scanf("%d%d",&u,&v);
        father[u]=v;
        dis[u]=abs(u-v)%1000;
    }

    else  if(c=='E')
    {int u;
        scanf("%d",&u);
        find(u);
        printf("%d\n",dis[u]);
    }



    }

}
return 0;
}