The topic is still the application of the collection, and the problem of the previous prison, the subject is calculated by distance, by recording the distance to their parent node relative distance, and the parent node to the root node (representing the element) is added in sequence
The node is updated each time the path is compressed.
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring>using namespace std; const int maxn=30001;int p;struct{int Father,tot,dis;} Block[maxn];void in () {for (int i=0;i<maxn;++i) {block[i].dis=0; Block[i].father=i; Block[i].tot=1; }}int Getanc (int a) {if (block[a].father==a) return A; int ret; Ret=getanc (Block[a].father); Block[a].dis+=block[block[a].father].dis; Block[a].father=ret; return ret;} void Union_set (int a,int b) {int Aa=getanc (a); int Bb=getanc (b); The block[bb].dis=block[aa].tot;//b element represents the element to represent the element's distance block[bb].father=aa;//b the element's parent node is updated Block[aa].tot+=block[bb].tot ;//The total number of elements is updated}void print (int a) {int aa=getanc (a); printf ("%d\n", block[aa].tot-block[a].dis-1); Represents the total number of elements-the current element to the distance representing the element-itself = the number of elements below}int main () {scanf ("%d", &p); char s; int x, y; In (); while (p--) {GetChar (); scanf ("%c", &s); if (s== ' M ') { scanf ("%d%d", &x,&y); Union_set (x, y); } else {scanf ("%d", &x);p rint (x);} } return 0;}
Poj1988cube Stacking (and check set + path compression)