Pa[i] Represents the father of I
Pre[i] On behalf of I how many
Sum[i] Represents the number of the whole column where I is located
CC is command type, x y is command parameter, FX FY is x y father
When cc== ' M ', merge x y, because X is placed in the queue where Y is located behind the queue, so Pre[fx]=sum[fy] (the rest of the pre is calculated in find), SUM[FY]+=SUM[FX]
When cc== ' C ', if X y is in a set, output abs (Pre[x]-pre[y])-1, ask is the number of the middle, so minus 1. If x y is not in a collection, output-1
In Find:
int Find (int x) { if(x!=pa[x]) { int tem=Find (pa[ X]);//First recursion pre[x]+ =pre[pa[x]];//x pre plus pa[x]. Note that this pa[x] has not yet done path compression pa[x]=tem;//path compression }return pa[x];}
Code:
#include <iostream>#include<cstring>#include<cstdlib>#defineSize 30005using namespacestd;intN;intPa[size];intSum[size],pre[size];voidinit () { for(intI=1; i<size;i++) pa[i]=i,sum[i]=1;}intFindintx) { if(x!=Pa[x]) { inttem=find (pa[x]); PRE[X]+=Pre[pa[x]]; PA[X]=tem; } returnpa[x];}BOOLQueryintXinty) { returnFind (x) = =find (y);}voidUnintXinty) { if(Query (x, y))return; Pa[find (x)]=find (y); }intMain () {init (); intT;cin>>T; Charccintx, y; while(t--) {cin>>cc>>x>>y; intFx=find (x);intfy=find (y); if(cc=='M') {un (x, y); PRE[FX]=Sum[fy]; SUM[FY]+=SUM[FX]; } Else{ if(fx==fy) Cout<<abs (Pre[x]-pre[y])-1<<Endl; Elsecout<<-1<<Endl; } }}
code1540 Galaxy Heroes Legend