Cube Stacking POJ1988 【並查集的應用】,stackingpoj1988
http://poj.org/problem?id=1988
Description
Farmer John and Betsy are playing a game with N (1 <= N <= 30,000)identical cubes labeled 1 through N. They start with N stacks, each containing a single cube. Farmer John asks Betsy to perform P (1<= P <= 100,000) operation. There are two types of operations:
moves and counts.
* In a move operation, Farmer John asks Bessie to move the stack containing cube X on top of the stack containing cube Y.
* In a count operation, Farmer John asks Bessie to count the number of cubes on the stack with cube X that are under the cube X and report that value.
Write a program that can verify the results of the game.
Input
* Line 1: A single integer, P
* Lines 2..P+1: Each of these lines describes a legal operation. Line 2 describes the first operation, etc. Each line begins with a 'M' for a move operation or a 'C' for a count operation. For move operations, the line also contains two integers: X and Y.For count operations, the line also contains a single integer: X.
Note that the value for N does not appear in the input file. No move operation will request a move a stack onto itself.
Output
Print the output from each of the count operations in the same order as the input file.
Sample Input
6M 1 6C 1M 2 4M 2 6C 3C 4
Sample Output
102
求出任何一個節點的下屬的個數
/*帶權並查集,一堆中最頂上的方塊作為父節點,用dis[X] 統計X到父親節點的距離,num[fa[X]]表示團的大小,兩者相減即為答案*/#include <stdio.h>#include <string.h>#define N 30000+100//結點個數int num[N];//記錄這個團隊的人數int dis[N];//記錄有個點到根節點的距離int per[N];//表示父節點void init(){ for(int i=0;i<N;++i) { num[i]=1; dis[i]=0; per[i]=i; }}int find(int x){ if(x==per[x]) return x; int t=per[x]; per[x]=find(per[x]); dis[x]+=dis[t];//當尋找一個數時, return per[x];}void join(int x,int y){ int fx=find(x); int fy=find(y); if(fx!=fy) { per[fy]=fx; dis[fy]=num[fx]; num[fx]+=num[fy]; }}int main(){ int n; int a,b; char ch; while(~scanf("%d",&n)) { init(); while(n--) { getchar(); scanf("%c",&ch); if(ch=='M') { scanf("%d%d",&a,&b); join(a,b); } else if(ch=='C') { scanf("%d",&a); int x=find(a); printf("%d\n",num[x]-dis[a]-1); } } } return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。