Test instructions: N Heap Box Initial i stacking box I. Q operation.
Action 1: Place the pile containing box x above the one containing the box Y. (x, Y is not operational in the same heap).
Action 2: Figure out how many boxes are below the X.
N<=3e4. Q<=1e6.
Use and check the same stack of boxes to connect together. Cnt[i] maintains the distance from each point to its root node (bottom box is root)
Cnt[fx]=sum[fy] when merging.
The FX-rooted node u, now with FY as the root in Find, will go through FX at this time to update its CNT.
#include <bits/stdc++.h>
#define REP (i,a,b) for (int i=a;i<=b;i++)
using namespace std;
typedef pair<int,int> II;
const int n=2e5+5;
int q,fa[n],sum[n],cnt[n];
void init ()
{
rep (i,0,n-1)
fa[i]=i,sum[i]=1,cnt[i]=0;
}
int find (int x)
{
if (x==fa[x])
return x;
int T=find (fa[x]);
CNT[X]+=CNT[FA[X]];
return fa[x]=t;
}
int main ()
{
init ();
int x, y;
cin>>q;
while (q--)
{
char op[2];
scanf ("%s", op);
if (op[0]== ' M ')
{
scanf ("%d%d", &x,&y);
int Fx=find (x), Fy=find (y);
if (fx==fy) continue;
Fa[fx]=fy;
CNT[FX]=SUM[FY];
SUM[FY]+=SUM[FX];
}
if (op[0]== ' C ')
{
scanf ("%d", &x);
int Fx=find (x);
printf ("%d\n", Cnt[x]);
}
}
return 0;
}