The main topic: some cubes, initially each cube in a separate stack, a total of n. Supports two operations, that is, to move the stack containing the cube to the top of the stack containing the cube (two stack merges) and the number of cubes below the query cube.
Idea: The stack top element is the representative element of each collection, and the path compresses the distance (dist[]) of each node to represent the element, and the number of elements (cnt[]) that are represented by each element.
The code is as follows:
#include <iostream>#include <cstdio>using namespace STD;Const intmaxn=30005;intM,FA[MAXN],CNT[MAXN],DIST[MAXN];intx, y;intFindintx) {if(fa[x]==x)returnXintFx=find (Fa[x]); DIST[X]+=DIST[FA[X]];returnFA[X]=FX;}voidUniteintXintY) {intFx=find (x);intFy=find (y); FA[FY]=FX; DIST[FY]=CNT[FX]; CNT[FX]+=CNT[FY];}intMain () {intx, y;CharChscanf("%d\n", &m); for(intI=1; i<=maxn;++i) {fa[i]=i; cnt[i]=1; dist[i]=0; } while(m--) {scanf("%c", &ch);if(ch==' M ') {scanf("%d%d\n", &x,&y); Unite (x, y); }Else{scanf("%d\n", &x);intFx=find (x);printf("%d\n", cnt[fx]-dist[x]-1); } }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
POJ1988 Cube Stacking