1. 程式人生 > >HDU - 3635 Dragon Balls 並查集

HDU - 3635 Dragon Balls 並查集

題解 log col ++ 暫時 include turn 數據 集合

題意:1~N個龍珠,放在1~N個城市,有兩種操作:T A B 將A所再城市的所有球轉移到B所在的城市。 Q X 詢問X所在的城市pls,該城市中龍珠數量nm,以及龍珠轉移次數trs

題解:並查集模板題,順帶更新一些數據。pls不必更新,因為X所在的集和的根即為城市編號。nm只需在union時將A集合根的nm加到B集合根的nm上,最後輸出根的nm。trs則是在每次T中對根++(暫時將操作存在根上),在下次find時,如果某個兒子換根了就更新下去,。。。

ac

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include
<stdio.h> #include<string> using namespace std; const int maxn = 1e4 + 5; struct ball { int fa,trs, nm;//place,total num,trans time }b[maxn]; int find(int x) { if (b[x].fa == x)return x; else { int tmp = b[x].fa; b[x]. fa = find(b[x].fa); b[x].trs += b[tmp].trs;
return b[x].fa; } }; void un(int x, int y) { int xx = find(x); int yy = find(y); if (xx != yy) { b[xx].fa = yy; b[yy].nm += b[xx].nm; b[xx].trs++; } }; int main() { int t; cin >> t; for (int k = 1; k <= t; k++) { printf(
"Case %d:\n", k); int n, q; cin >> n >> q; for (int i = 1; i <= n; i++) b[i].nm = 1, b[i].trs= 0,b[i].fa=i; for (int i = 1; i <= q; i++) { char c[5]; scanf("%s", c); if (c[0] == T) { int x, y; scanf("%d%d", &x, &y); un(x, y); } else { int x; scanf("%d", &x); int xx = find(x); printf("%d %d %d\n",xx, b[xx].nm, b[x].trs); } } } }

HDU - 3635 Dragon Balls 並查集