1 条题解

  • 1
    @ 2022-12-13 10:58:46
    #include<cstdio>
    #include<iostream>
    using namespace std;
    const int maxn = 5e5+5;
    int fa[maxn],d[maxn],l[maxn],n,p;
    inline int read()
    {
        char c = getchar();int x = 0,f = 1;
        while(c<'0'||c>'9') {if(c=='-')f = -1;c = getchar();}
        while(c>='0'&&c<='9') {x = x*10+c-'0';c = getchar();}
        return x*f;
    }
    //路径压缩+带权并查集标准写法,由于d[i]维护答案,直传它的值
    int find(int x)
    {
        if(x==fa[x])
            return x;
        int last = find(fa[x]);
        d[x] += d[fa[x]];
        return fa[x] = last;
    }
    //因为选用了最下面一个积木作为根,所以要用祖先来更新。
    void update(int x,int y)
    {
        x = find(x);y = find(y);
        if(x!=y)
        {
            fa[x] = y;
            d[x] = l[y];
            l[y] += l[x];
        }
    }
    int main()
    {
        for(int i = 1;i<=maxn;++i)
            fa[i] = i,l[i] = 1;
        int p = read();
        for(int i = 1;i<=p;++i)
        {
            char c; cin >> c;
            if(c=='M')
            {
                int x = read();int y = read();
                update(x,y);
            }
            else
            {
                int x = read();
                find(x);
                printf("%d\n",d[x]);
            }
        }
        return 0;
    }
    
    • 1

    【提高】立方体积木Cube Stacking

    信息

    ID
    922
    时间
    1000ms
    内存
    128MiB
    难度
    6
    标签
    递交数
    54
    已通过
    19
    上传者