UVA 11987 Almost Union-Find 并查集(建立虚点)

题目链接

题意

给定1到n的数列分别处在1到n的集合中,有以下三种操作

  1. 1 x y 表示把x所在的集合和y所在的集合合并(如果x和y已经在一个集合中,忽略此操作)
  2. 2 x y 表示将x移动到y所在的集合中(如果x和y已经在一个集合中,忽略次操作)
  3. 3 x 询问x所在的集合的元素个数和元素之和

分析

单从1和3的询问来看,就是一个并查集的模板题,但是如何去维护操作2呢。我们肯定不能直接将x合并到y中,因为x肯定有自己的子树,如果移动了x,那么x的子树上的点就没办法正确找到祖先。我们发现其实在操作二中只有一个节点发生了改变,那么我们可以建立一个新的节点代表x,但不删除之前的旧节点从而把原来旧的贡献减掉就可以了。

新建节点操作

void newnode(int x) {
    id[x] = ++n;
    ans[id[x]] = x;
    num[id[x]] = 1;
    fa[id[x]] = id[x];
}

减去原来的贡献

void move(int x) {
    int fx = find(id[x]);
    ans[fx] -= x;
    num[fx]--;
    newnode(x);
}

完整代码

#include <bits/stdc++.h>
#define ACM_LOCAL
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 5e5 + 10, M = 5e5 + 10, INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
int fa[N], id[N], num[N], n, m;;
ll ans[N];
int find(int x) {return fa[x] == x ? x : fa[x] = find(fa[x]);}
void merge(int x, int y) {
    int fx = find(x), fy = find(y);
    ans[fy] += ans[fx];
    num[fy] += num[fx];
    fa[fx] = fy;
}

void newnode(int x) {
    id[x] = ++n;
    ans[id[x]] = x;
    num[id[x]] = 1;
    fa[id[x]] = id[x];
}

void move(int x) {
    int fx = find(id[x]);
    ans[fx] -= x;
    num[fx]--;
    newnode(x);
}

void solve() {
    while (cin >> n >> m) {
        for (int i = 1; i <= n; i++) fa[i] = i, ans[i] = i, num[i] = 1, id[i] = i;
        for (int i = 1; i <= m; i++) {
            int opt, x, y; cin >> opt;
            if (opt == 1) {
                cin >> x >> y;
                if (find(id[x]) == find(id[y])) continue;
                merge(id[x], id[y]);
            } else if (opt == 2) {
                cin >> x >> y;
                if (find(id[x]) == find(id[y])) continue;
                move(x); merge(id[x], id[y]);
            } else {
                cin >> x;
                x = find(id[x]);
                printf("%d %lld\n", num[x], ans[x]);
            }
        }
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#ifdef ACM_LOCAL
    freopen("input", "r", stdin);
    freopen("output", "w", stdout);
#endif
    solve();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值