Algorithm concept: weighted and query set.
However, pay attention to the selection of "Weights". The following code uses the solution: Save the distance from each node to its parent node at the beginning. d [I], when a findset operation is performed, compress the path and sequentially update the d [I] of each node on the path so that the D [I] at this time is the distance from the node to the root node, after findset is executed, cout <D [I] is the result of the question. (This cainiao personally thinks that this idea is classic and representative, which helps to inspire similar things)
Code Source: Liu rujia-an entry to the informatics competition (strongly recommended, rare good book)
// Template start # include <string> # include <vector> # include <algorithm> # include <iostream> # include <sstream> # include <fstream> # include <map> # include <set> # include <cstdio> # include <cmath> # include <cstdlib> # include <ctime> # include <iomanip> # define SZ (X) (INT (X. size () using namespace STD; int toint (string s) {istringstream sin (s); int t; sin> T; return t ;} template <class T> string tostring (t x) {ostrings Tream sout; sout <X; return sout. STR ();} typedef long int64; int64 toint64 (string s) {istringstream sin (s); int64 t; sin> T; return t ;} template <class T> T gcd (t a, t B) {if (a <0) return gcd (-a, B); If (B <0) return gcd (A,-B); Return (B = 0 )? A: gcd (B, A % B);} // end of the template (General Part) # define ifs cinconst int maxn = 20000 + 10; int pa [maxn], d [maxn]; int findset (int x) {If (PA [x]! = X) {int root = findset (PA [x]); D [x] + = d [PA [x]; return pa [x] = root ;} else {return x ;}// la 3027 actual ative networkint main () {// ifstream ifs ("shuju.txt", IOS: In); int t; ifs> T; while (t --) {int N, U, V; char cmd [9]; ifs> N; For (INT I = 1; I <= N; I ++) // initialization. Each node is a separate tree {pa [I] = I; d [I] = 0;} while (IFS> cmd & cmd [0]! = 'O') {If (CMD [0] = 'E') {ifs> U; findset (U ); cout <D [u] <Endl;} If (CMD [0] = 'I') {ifs> U> V; PA [u] = V; d [u] = ABS (u-v) % 1000 ;}} return 0 ;}