并查集初学(2)LA 3644 & LA3027

1、LA 3644


题目:http://acm.hust.edu.cn:8080/judge/problem/viewProblem.action?id=12648


并查集入门题,寻找是否存在环,若存在,则cnt++


#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

const int maxn=100010;

using namespace std;

int p[maxn];
//带路径压缩的并查集
int Find(int x){return p[x] == x?x:p[x]=Find(p[x]);}

int main()
{
    int x,y;
    while (scanf("%d",&x) == 1)
    {
        for (int i=0;i<maxn;i++) p[i]=i;
        int cnt=0;
        while (x != -1)
        {
            scanf("%d",&y);
            x=Find(x);
            y=Find(y);
            if (x == y) cnt++;
            else p[x]=y;
            scanf("%d",&x);
        }
        printf("%d\n",cnt);
    }
    return 0;
}
 
 
 
 


2、LA 3027


题目:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=33982

分析:一边路径压缩,一边维护d[i] : 结点i到树根的距离

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int maxn=20010;

int p[maxn];
int d[maxn];

int Find(int x)
{
    if (p[x] != x)
    {
        int root=Find(p[x]);
        d[x] += d[p[x]];
        return p[x]=root;
    }
    else return x;
}

int main()
{
    int T;
    scanf("%d",&T);
    while (T--)
    {
        int n,u,v;
        char cmd[9];
        scanf("%d",&n);
        for (int i=1;i<=n;i++)
        {
            p[i]=i;
            d[i]=0;
        }
        while (scanf("%s",cmd) && cmd[0] != 'O')
        {
            if (cmd[0] == 'I')
            {
                scanf("%d%d",&u,&v);
                p[u]=v;
                d[u]=abs(u-v) % 1000;
            }
            if (cmd[0] == 'E')
            {
                scanf("%d",&u);
                int t=Find(u);
                printf("%d\n",d[u]);
            }
        }
    }
    return 0;
}


 


你可能感兴趣的:(la,3644,LA3027)