1 /*2 There are n enterprises, each enterprise want to achieve communication, to connect with the line, the length of the line is abs (A-B)%1000;3 If enterprise A is linked to Enterprise B then B is the center of the serving!4 Then there are two kinds of actions:5 E A: The distance from Enterprise A to the serving center line6 I A, B connects enterprise A to Enterprise B, then B becomes the serving center (before the enterprise that connects a, their serving center becomes b)7 8 ideas: and check set! (Backtracking solution when compressing paths)! 9 */ Ten#include <iostream> One#include <cstring> A#include <cmath> -#include <cstdio> - #defineM 20005 the using namespacestd; - intN; - intF[m]; - intANS[M];//the distance from node I to serving center! + - intGetfather (intx) { + if(X==f[x])returnx; A intHfSGetfather (f[x]); atANS[X]+=ANS[F[X]];//The distance from node X to serving center is added to the distance from the parent node to serving center! - returnf[x]=ff; - } - - voidUnion (intAintb) { - if(a==b)return; inf[a]=b; -Ans[a]=abs (A-B)% +; to } + - intMain () { the intT; * Charch[3]; $Cin>>T;Panax Notoginseng while(t--){ -Cin>>N; the intA, B; +memset (ans,0,sizeof(ans)); A for(intI=1; i<=n; ++i) thef[i]=i; + while(Cin>>ch && ch[0]!='O'){ - if(ch[0]=='E'){ $Cin>>A; $ Getfather (a); -cout<<ans[a]<<Endl; - } the Else{ -Cin>>a>>b;Wuyi Union (A, b); the } - } Wu } - return 0; About}