POJ 1988 Cube Stacking (帶權並查集)
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
6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4
Sample Output
1
0
2
題意:
起初有N個方塊堆,有兩種操作,M是移動含有X的方塊堆到含有Y的方塊堆上,C是計算有多少個方塊堆在X的下面。
題解:
經典好題! 很容易想到用並查集來維護移動後方塊堆的關系,但是怎麽維護方塊之間的順序關系呢,或者說怎麽知道某個方塊下面有多少個方塊呢?我們可以開個dis數組記錄方塊到根節點的距離,num數組記錄當前堆中方塊數量。假設有A->B->C從高到底的三個方塊,那麽dis[A->C]=dis[B->C]+dis[A->B]。需要註意的是路徑壓縮的時候,遞歸求節點到根節點的距離,具體請看代碼。
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=3e4+5;
int par[maxn];
int dis[maxn],num[maxn];//dis為到根節點的距離,只有當該結點直接連接根節點時,這個值才有效。
//num[i]為i所在的堆的所有立方體數量
void init()
{
for(int i=0;i<=maxn;i++)
par[i]=i,dis[i]=0,num[i]=1;
}
int find(int x)
{
if(par[x]==x)
return x;
int fa=par[x];//
par[x]=find(par[x]);//路徑壓縮,註意這兩步,一定要理解遞歸
dis[x]+=dis[fa];//此時x的父親節點已經連接到根節點上了
return par[x];
}
void unite(int x,int y)
{
x=find(x),y=find(y);
if(x==y)
return ;
par[x]=y;
dis[x]+=num[y];
num[y]+=num[x];//兩個堆合並
}
int main()
{
init();
int n;
cin>>n;
while(n--)
{
char op;
cin>>op;
if(op=='M')
{
int x,y;
cin>>x>>y;
unite(x,y);
}
else
{
int x;
cin>>x;
find(x);//輸出前對dis[a]進行更新
cout<<dis[x]<<endl;
}
}
return 0;
}
POJ 1988 Cube Stacking (帶權並查集)