[POJ 1988] Cube Stacking
we need to add two properties cnt [i] cnt [i] and s [i] s [i]respectively, the number represents the number of blocks is located below the stack and ii ii. When the compression path, cnt [i] + = cntAlso in the connecting operation, need to dynamically update the information cnt [find (u)] and s [find (v)] of.
. 1 #include <the iostream> 2 #define LSON L, m, RT <<. 1 . 3 #define rson. 1 + m, R & lt, RT. 1 << |. 1 . 4 #define ClO iOS STD :: :: sync_with_stdio (to false) . 5 the using namespace STD; . 6 const int MAXN = 1E5 + . 5 ; . 7 const int N = 300004 ; . 8 int F [N], CNT [N], S [N]; . 9 void the init () { 10 for ( int I = . 1 ; I <= N; I ++ ) { . 11 // each their roots are initialized, and where only one stack 12 is F [I] = I; 13 is S [I] = . 1 ; 14 } 15 } 16 . 17 int Find ( int X) { 18 is int RT; . 19 // value cnt update path when compressed, the root of each pile is the lowermost 20 is IF (F [X] =! X) { 21 is int FA = F [X]; 22 is F [X] = Find (F [X]); 23 is CNT [X] + = CNT [FA] ; 24 } 25 // no compression with the path 26 is return F [X]; 27 } 28 int main(){ 29 std::ios::sync_with_stdio(false); 30 int p;cin>>p; 31 init(); 32 while(p--){ 33 //cout <<"p=="<<p<<endl; 34 char c; 35 cin>>c; 36 if(c=='M') 37 { 38 int a,b;cin>>a>>b; 39 int fa=find(a);int fb=find(b); 40 if(fa!=fb){ 41 f[fa]=fb; 42 cnt[fa]=s[fb]; 43 s[fb]+=s[fa]; 44 } 45 } 46 else 47 { 48 int u; 49 cin>>u; 50 find(u); 51 cout <<cnt[u]<<endl; 52 } 53 } 54 return 0; 55 }