uva11987

题意是实现一个带删除功能的并查集。

这题的做法是,比如你要删除x,你就相当于把x剥离出来,开一个新的点去记录新的x,同时把原来x的父节点fa[x]做关于删除x节点信息的操作。

#include <cstdio>

using namespace std;

const int maxn = 1000000 + 5;

int n, m, tot;

int id[maxn * 2], fa[maxn], cnt[maxn], sum[maxn];

int find(int x)
{
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}

void Union(int x, int y)
{
    int fx = find(x), fy = find(y);
    if (fx != fy)
    {
        fa[fx] = fy;
        cnt[fy] += cnt[fx];
        sum[fy] += sum[fx];
    }
}

void del(int x)
{
    int fx = find(id[x]);
    sum[fx] -= x;
    cnt[fx]--;
    tot++;
    id[x] = tot;
    fa[tot] = tot;
    sum[tot] = x;
    cnt[tot] = 1;
}

int main()
{
//    freopen("uva11987.in","r",stdin);
    while (~scanf("%d%d", &n, &m))
    {
        tot = n;
        for (int i = 1; i <= n; i++)
        {
            id[i] = fa[i] = sum[i] = i;
            cnt[i] = 1;
        }
        for (int i = 1; i <= m; i++)
        {
            int op;
            scanf("%d", &op);
            if (op == 1) 
            {
                int x, y;
                scanf("%d%d", &x, &y);
                Union(id[x], id[y]);
            }
            else
            if (op == 2)
            {
                int x, y;
                scanf("%d%d", &x, &y);
                int fx = find(id[x]);
                int fy = find(id[y]);
                if (fx != fy)
                {
                    del(x);
                    Union(id[x], id[y]);
                }
            }
            else
            if (op == 3)
            {
                int x;
                scanf("%d", &x);
                int fx = find(id[x]);
                printf("%d %d\n", cnt[fx], sum[fx]);
            }
        } 
    }
    return 0;
}

 

posted @ 2017-11-08 20:17  yohanlong  阅读(130)  评论(0编辑  收藏  举报