zoukankan      html  css  js  c++  java
  • UVA 11987 Almost UnionFind

    UVA_11987

        操作2实际上相当于先把x删掉然后再和y合并,因此和普通的并查集相比只是多了一个删除某个点的操作。

        对于删除操作,是不能随便改变原来树中p[]的指向的,比较容易能够举出反例。其实我们只是想在不影响其他元素的前提下把x删掉,但不如换个思路,将x这个点对它所在的集合的“影响”变为0。然后再新开一个节点表示x,这样就相当于把x从原来的集合中剥离出来了。因此相比原来的并查集,需要多一个id[x]数组表示点x现在的标号,有了上面的思路其余的操作就不难写出来了。

    #include<stdio.h>
    #include<string.h>
    #define MAXD 200010
    int N, M, p[MAXD], id[MAXD], num[MAXD], cnt;
    long long sum[MAXD];
    void init()
    {
        int i;
        for(i = 1; i <= N; i ++) id[i] = p[i] = sum[i] = i, num[i] = 1;
        cnt = N;
    }
    int find(int x)
    {
        return p[x] == x ? x : (p[x] = find(p[x]));    
    }
    void Union(int x, int y)
    {
        int tx = find(id[x]), ty = find(id[y]);
        p[tx] = ty, num[ty] += num[tx], sum[ty] += sum[tx];    
    }
    void Delete(int x)
    {
        int tx = find(id[x]);
        -- num[tx], sum[tx] -= x;
        id[x] = ++ cnt, p[id[x]] = id[x], num[id[x]] = 1, sum[id[x]] = x;    
    }
    void solve()
    {
        int i, x, y, op;
        for(i = 0; i < M; i ++)
        {
            scanf("%d", &op);
            if(op == 1)
            {
                scanf("%d%d", &x, &y);
                if(find(id[x]) != find(id[y])) Union(x, y);
            }
            else if(op == 2)
            {
                scanf("%d%d", &x, &y);
                if(find(id[x]) != find(id[y])) Delete(x), Union(x, y);
            }
            else
            {
                scanf("%d", &x);
                printf("%d %lld\n", num[find(id[x])], sum[find(id[x])]);
            }
        }
    }
    int main()
    {
        while(scanf("%d%d", &N, &M) == 2)
        {
            init();
            solve();    
        }
        return 0;    
    }
  • 相关阅读:
    jq隐藏页面的一行(循环隐藏10行)
    Button的OnClientClick()事件不起作用?
    Infopath自定义表单实现列表字段联动
    SharePoint 2013的传出电子邮件设置
    codeforces Looksery Cup 2015 D. Haar Features
    codeforces Looksery Cup 2015 H Degenerate Matrix
    poj3321 Apple Tree
    poj1990 MooFest
    poj2155 Matrix
    hdu1556 Color the ball
  • 原文地址:https://www.cnblogs.com/staginner/p/2651046.html
Copyright © 2011-2022 走看看