Main topic:
Some warships, initially each in their own number corresponding to the queue, now has two operations:
M a B: The order of the queue where a battleship is located is connected to the tail of the B battleship's queue.
C a B: Ask a b about the distance between the same queue if a B is not in the same queue output-1 idea:
Obviously and check the set of routines but I began to think of a bifurcation, thought that only with a dis array to maintain the distance between the child and ancestors is enough, but found that the merger is not right, such as the merge (a, b) I was the beginning of the dis[fb]=dis[a]+1; But suddenly found that the input to you is a queue of any one of the warships, and I started with a as a in the queue of the tail ship to update, obviously this does not, then you will want to know when the merger of the queue I want to pick up on him how long to change their own dis, Then add a num array to record the number of warships per queue. Code:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include < string> #include <vector> #include <stack> #include <bitset> #include <cstdlib> #include <
cmath> #include <set> #include <list> #include <deque> #include <map> #include <queue>
using namespace Std;
typedef long Long LL;
Const double PI = ACOs (-1.0);
Const double EPS = 1e-6;
const int INF = 1000000000;
const int MAXN = 34567;
int t,n,m;
int F[MAXN];
int dis[maxn];//the distance from the root int num[maxn];//The total number of warships in the queue void init () {for (int i=0;i<=30000;i++) {f[i]=i;
dis[i]=0;
Num[i]=1;
}} int Get_f (int x)//and check set path compression {if (f[x]==x) return x;
else {int fa=get_f (f[x]);
DIS[X]+=DIS[F[X]];
return F[X]=FA;
}} void Merge (int v,int u)//merge {int vv=get_f (v);
int uu=get_f (u);
if (Vv!=uu) {f[vv]=uu;
DIS[VV]=NUM[UU]; Num[uu]+=num[vV];
num[vv]=0;
}} int main () {init ();
scanf ("%d", &t);
Char op[2];
int A, B;
while (t--) {scanf ("%s%d%d", op,&a,&b);
if (op[0]== ' M ') {Merge (A, b);
} else {int aa=get_f (a);
int Bb=get_f (b);
if (AA!=BB) printf (" -1\n");
else printf ("%d\n", ABS (Dis[a]-dis[b])-1);
}} return 0; }