[並查集]銀河宇宙傳說 題解
阿新 • • 發佈:2021-08-07
( ゚∀゚)o彡゜ ヒーコー ヒーコー!#include <stdio.h> inline int abs (const int &x) { return x < 0 ? -x : x; } int n; int fa[30003]; // 當前節點所在樹的首領 int s[30003]; // 當前首領所在樹的節點數量 int d[30003]; // 當前節點與所在樹首領中的節點數量 #define fa(x) fa[x] #define size(x) s[x] #define dis(x) d[x] inline int get (int x) { if (fa(x) == x) return x; int grandfather = get(fa(x)); dis(x) += dis(fa(x)); fa(x) = grandfather; return fa(x); } int main () { scanf("%d", &n); for (int i = 1; i < 30003 ; i++) { fa(i) = i; size(i) = 1; dis(i) = 0; } for (int i = 1; i <= n; i++) { char ch[4]; int x, y; scanf("%s %d %d", &ch, &x, &y); int fx = get(x), fy = get(y); // x/y 所在樹首領 if (ch[0] == 'M') { fa(fx) = fy; // x 所在樹併入 y 所在樹, 即 fx 的首領變為 fy dis(fx) = size(fy); // fx 距 fy 的距離即更新前 y/fy 所在樹的節點總數 size(fy) += size(fx); // y 所在樹節點總數更新 } else printf("%d\n", fx == fy ? abs(dis(x) - dis(y)) - 1 : -1); } return 0; }