第十四届华中科技大学程序设计竞赛C 可删除元素的并查集

链接: https://www.nowcoder.com/acm/contest/106/C
来源:牛客网

题目描述

It’s universally acknowledged that there’re innumerable trees in the campus of HUST. 

Thus a professional tree manager is needed. Your task is to write a program to help manage the trees. 
Initially, there are n forests and for the i-th forest there is only the i-th tree in it. Given four kinds of operations.

1 u v, merge the forest containing the u-th tree and the forest containing the v-th tree;

2 u, separate the u-th tree from its forest;

3 u, query the size of the forest which contains the u-th tree;
4 u v, query whether the u-th tree and the v-th tree are in the same forest.

输入描述:

 
 

The first line contains an integer T, indicating the number of testcases.

In each test case:

The first line contains two integers N and Q, indicating the number of initial forests and the number of operations.

Then Q lines follow, and each line describes an operation.

输出描述:

For each test cases, the first line should be "Case #i:", where i indicate the test case i.
For each query 3, print a integer in a single line.
For each query 4, print "YES" or "NO" in a single line.

题解:对每个节点都编号,然后查询都用编号去查询即可。

#include <bits/stdc++.h>

using namespace std;

const int maxn = 2e5 + 7;
int par[maxn], id[maxn], cnt[maxn];

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

int main()
{
    //freopen("f:\\zxc.txt","w",stdout);
    int T, Case = 0;
    scanf("%d", &T);
    while(T --) {
        memset(cnt, 0, sizeof(cnt));
        int n, q;
        printf("Case #%d:\n", ++Case);
        scanf("%d %d", &n, &q);
        for(int i = 1;i <= n;i ++) cnt[i] = 1, id[i] = par[i] = i;
        int vir = n + 1;
        while(q --) {
            int opt;
            scanf("%d", &opt);
            if(opt == 1) {
                int u, v;
                scanf("%d %d", &u, &v);
                u = find(id[u]);
                v = find(id[v]);
                if(u == v) continue;
                par[u] = v;
                cnt[v] += cnt[u];
                cnt[u] = 0;
            } else if(opt == 2) {
                int u;
                scanf("%d", &u);
                int paru = find(id[u]);
                cnt[paru] --;
                id[u] = vir ++;
                cnt[id[u]] = 1;
                par[id[u]] = id[u];
            } else if(opt == 3) {
                int u;
                scanf("%d", &u);
                u = id[u];
                printf("%d\n", cnt[find(u)]);
            } else {
                int u, v;
                scanf("%d %d", &u, &v);
                puts(find(id[u]) == find(id[v]) ? "YES" : "NO");
            }
        }
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值