Topic Portal
Test Instructions: Training guide P192
Analysis: The main is a path in the process of compression, update the point I to the root of the distance
#include <bits/stdc++.h>using namespace Std;const int N = 2e4 + 5;struct dsu{int rt[n], d[n];void init (void) {memset (RT,-1, sizeof (RT)); Memset (d, 0, sizeof (d)); int find (int x) {if (rt[x]! =-1) {int root = find (rt[x]);//Find root d[x] + = d[rt[x]];//backtracking process distance update return rt[x] = root;//path compression}els Ereturn x;} void Union (int x, int y) {if (x = = y) {d[x] = 0;return;} ELSE{RT[X] = y;d[x] = ABS (x-y)% 1000;}} bool Same (int x, int y) {return find (x) = = Find (y);}} Dsu;int Main (void) {int t;scanf ("%d", &t), while (t--) {int n;scanf ("%d", &n), Char str[3];d su.init (); int x, Y;whil E (scanf ("%s", str) = = 1) {if (str[0] = = ' O ') break;if (str[0] = = ' E ') {scanf ("%d", &x);d su. Find (x);p rintf ("%d\n", Dsu.d[x]);} ELSE{SCANF ("%d%d", &x, &y);d su. Union (x, y);//initial is the distance to FA}}}return 0;}
and check set (path update) LA 3027 corporative Network