SOL: it is still a collection of water and water. However, we need to maintain a DIST array here (Dist is the distance from each node to its father's day point. It can be maintained during path compression !!!)
# Include <cstdio> # include <algorithm> # include <cmath> using namespace STD; const int maxn = 20000 + 10; int pa [maxn], DIST [maxn]; inline int findset (int x) {If (PA [x]! = X) {int root = findset (PA [x]); Dist [x] + = DIST [PA [x]; return pa [x] = root ;} else return X;} int main () {int t; scanf ("% d", & T); While (t --) {int N, U, V; char cmd [10]; scanf ("% d", & N); For (INT I = 1; I <= N; I ++) {pa [I] = I; Dist [I] = 0;} while (~ Scanf ("% s", CMD) & cmd [0]! = 'O') {If (CMD [0] = 'E') {scanf ("% d", & U); findset (U ); printf ("% d \ n", DIST [u]);} If (CMD [0] = 'I') {scanf ("% d ", & U, & V); PA [u] = V; Dist [u] = ABS (u-v) % 1000 ;}} return 0 ;}