標籤:http io ar for cti sp 代碼 on c
題目: UVALive - 3027Corporative Network(帶權並查集)
題目大意:有n和節點,初始時每個節點的父節點都不存在,然後有下面兩種操作:I 操作 I a,b 將a的父節點變成b。E操作 E a,查詢a到它的父節點的距離。
解題思路:帶權並查集。注意這裡距離的變化是a -> b,那麼a到根節點的距離就是a到b的距離的絕對值 % 1000 + b到它的根節點的距離。
代碼:
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 2e5 + 5;int p[maxn], c[maxn];int n;void init () {for (int i = 1; i <= n; i++) {p[i] = i;c[i] = 0;}}int getParent (int a) {if (a == p[a])return a;int t = p[a];p[a] = getParent (p[a]);c[a] += c[t];return p[a];}int main () {int T;int a, b;char str[10];scanf ("%d", &T);while (T--) {scanf ("%d", &n);init();while (scanf ("%s", str) != EOF) {if (str[0] == 'O')break;if (str[0] == 'E') {scanf ("%d", &a);int q1 = getParent (a);printf ("%d\n", c[a]);} else {scanf ("%d%d", &a, &b);p[a] = b;c[a] = abs (a - b) % 1000;}}}return 0;}
UVALive - 3027Corporative Network(帶權並查集)