LA 3027(p192)----Corporative Network

#include<bits/stdc++.h>
#define debu
using namespace std;
const int maxn=2*1e4+50;
int fa[maxn],ans[maxn],n;
int Find(int x)
{
    if(x!=fa[x])
    {
        int root=Find(fa[x]);
        ans[x]+=ans[fa[x]];
        return fa[x]=root;
    }
    else return x;
}
void init()
{
    memset(ans,0,sizeof(ans));
    for(int i=0; i<=n; i++) fa[i]=i;
}
int main()
{
#ifdef debug
    freopen("in.in","r",stdin);
    // freopen("out.out","w",stdout);
#endif // debug
    int t;
    scanf("%d",&t);
    while(t--)
    {
        char ch;
        scanf("%d\n",&n);
        init();
        while(scanf("%c",&ch)&&ch!='O')
        {
            if(ch=='I')
            {
                int x,y;
                scanf("%d%d\n",&x,&y);
                // cout<<x<<" "<<y<<endl;
                fa[x]=y;
                ans[x]=abs(x-y)%1000;
                //    cout<<ans[x]<<endl;
            }
            else
            {
                int x;
                scanf("%d\n",&x);
                //  cout<<x<<endl;
                Find(x);
                printf("%d\n",ans[x]);
            }
        }
    }
    return 0;
}

题目地址:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1028

题解:并查集。ans[i]表示i到其父节点的距离,路径压缩时更新这个数组即可。

非递归:

void Find(int root)
{
    int k,j,x,sum=0;
    x=root;
    while(x!=fa[x])
    {
        sum+=ans[x];
        x=fa[x];
    }
    k=root;
    while(k!=x)
    {
        sum-=ans[k];
        ans[k]+=sum;
        j=fa[k];
        fa[k]=x;
        k=j;
    }
}


你可能感兴趣的:(LA 3027(p192)----Corporative Network)