The so-called right-and-check set
The subject is not only the relationship between the two numbers, but also the relationship between the two numbers, which requires us to maintain multiple arrays, fa[] array maintain the connectivity between the two numbers, dis[] maintain the distance between the battleship of the number I to fa[i], num[] How many warships are there in the column that maintains the battleship number I?
Find function
int find (int x) {
if (X!=fa[x]) {
int k=fa[x];
Fa[x]=find (Fa[x]);
DIS[X]+=DIS[K];
NUM[X]=NUM[FA[X]];
}
return fa[x];
}
Update the NUM array with the DIS array every time you find
Merging functions
void merge (int x,int y) {
int r1=find (x), R2=find (y);
if (R1!=R2) {
fa[r1]=r2;
DIS[R1]=DIS[R2]+NUM[R2];
NUM[R2]+=NUM[R1];
NUM[R1]=NUM[R2];
}
}
The merger was due to the column I was in and to the end of the column where J was located, so DIS[R1]=DIS[R2]+NUM[R2].
Inquiry function
int query (int a,int b) {
int r1=find (a), r2=find (b);
if (R1!=R2) {
return-1;
} else {
return abs (Dis[a]-dis[b])-1;
}
}
Note that when you return, add a
AC Code:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace
Std
const int maxn=30005;
int read () {int rv=0,fh=1;
Char C=getchar (); while (c< ' 0 ' | |
C> ' 9 ') {if (c== '-') fh=-1;
C=getchar ();
} while (c>= ' 0 ' &&c<= ' 9 ') {rv= (rv<<1) + (rv<<3) +c-' 0 ';
C=getchar ();
} return RV*FH;
} int FA[MAXN],DIS[MAXN],T,NUM[MAXN];
int find (int x) {if (x!=fa[x]) {int k=fa[x];
Fa[x]=find (Fa[x]);
DIS[X]+=DIS[K];
NUM[X]=NUM[FA[X]];
} return fa[x];
} void Merge (int x,int y) {int r1=find (x), R2=find (y);
if (R1!=R2) {FA[R1]=R2;DIS[R1]=DIS[R2]+NUM[R2];
NUM[R2]+=NUM[R1];
NUM[R1]=NUM[R2];
}} int query (int a,int b) {int r1=find (a), r2=find (b);
if (R1!=R2) {return-1;
}else {return abs (Dis[a]-dis[b])-1;
}} int main () {freopen ("In.txt", "R", stdin);
T=read (); Forint i=1;i<=maxn;i++) {fa[i]=i;num[i]=1;}
for (int i=1;i<=t;i++) {char C;
scanf ("%c", &c);
int A=read (), B=read ();
if (c== ' M ') {merge (A, b);
}else {printf ("%d\n", query (b));
}} fclose (stdin);
return 0; }