zoukankan      html  css  js  c++  java
  • 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
    ", cnt[fx], sum[fx]);
                }
            } 
        }
        return 0;
    }
  • 相关阅读:
    hdu1074Doing Homework
    1088滑雪
    hdu1078FatMouse and Cheese
    hdu1058Humble Numbers
    hdu1114 Piggy-Bank
    hdu1069Monkey and Banana
    未解决的问题_c#中,最小化触发事件
    WPF Button 样式资源设置&后台生成button样式
    .NET 调用外部exe程序,出现已停止工作
    json类序列化与反序列化参考
  • 原文地址:https://www.cnblogs.com/yohanlong/p/7805947.html
Copyright © 2011-2022 走看看