UVA 11987,uva11987

來源:互聯網
上載者:User

UVA 11987,uva11987
UVA 11987 - Almost Union-Find

題目連結

題意:給定一些集合,操作1是合并集合,操作2是把集合中一個元素移動到另一個集合,操作3輸出集合的個數和總和

思路:並查集,關鍵在於操作2,對於並查集,要去除掉一個結點,如果該結點不是根那就好辦了,那麼就多開n個結點,每個結點初始父親都是它的i + n,這樣在移動的時候,就不用擔心他是根結點了剩下就是普通的帶權並查集了

代碼:

#include <cstdio>#include <cstring>const int N = 200005;int n, m, parent[N], num[N], sum[N];int find(int x) {    return x == parent[x] ? x : parent[x] = find(parent[x]);}void init() {    for (int i = 0; i <= n; i++) {parent[i] = parent[i + n] = i + n;sum[i] = sum[i + n] = i;num[i] = num[i + n] = 1;    }}int main() {    while (~scanf("%d%d", &n, &m)) {int q, a, b;init();while (m--) {    scanf("%d", &q);    if (q == 1) {scanf("%d%d", &a, &b);int pa = find(a);int pb = find(b);if (pa == pb) continue;parent[pa] = pb;num[pb] += num[pa];sum[pb] += sum[pa];    }    else if (q == 2) {scanf("%d%d", &a, &b);int pa = find(a);int pb = find(b);if (pa == pb) continue;parent[a] = pb;num[pa]--;num[pb]++;sum[pa] -= a;sum[pb] += a;    }    else {scanf("%d", &a);int pa = find(a);printf("%d %d\n", num[pa], sum[pa]);    }}    }    return 0;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.