POJ 1988 Cube Stacking

* 1988 Cube Stacking
* 题意给你 1-n 编号的立方体,然后移动含有指定编号的立方体
* 栈移到另一个栈上边,问指定的编号立方体下面有多少个立方体。
*
* 应用 并查集的思路,移动一个栈时,相当于union_set操作,只要另开一个
* 数组记录立方体的位置,当合并时,只要改变根节点的位置记录就可以了,
* 这个地方并查集用的比较巧妙。其余的就是基本的并查集操作了。
* */
#include<iostream>
using namespace std;
int cube[30330],nr[30330];
int n;
void make_set()
{
    
for(int i=0;i<=30030;++i)
    {
        cube[i] 
= -1;
        nr[i] 
= 0;
    }
}
int find_set(int x)
{
    
int tmp = cube[x];
    
if(cube[x]<0)
        
return x;
    cube[x] 
= find_set(cube[x]);
    nr[x] 
+= nr[tmp];
    
return cube[x];
}
void union_set(const int& root1,const int& root2)
{
    
int tmp = cube[root1];
    cube[root1] 
= root2;
    nr[root1] 
=nr[root1] - cube[root2];
    cube[root2] 
+= tmp;
}
int main()
{
    
int i,j,root1,root2,n1,n2;
    
char ch[1];
    cin
>>n;
    make_set();
    
while(n--)
    {
        scanf(
"%s ",ch);    
        
if(ch[0]=='M')
        {
            scanf(
"%d%d",&n1,&n2);
            
int root1 = find_set(n1);
            
int root2 = find_set(n2);
            
if(root1!=root2)
                union_set(root1,root2);
        }
else if(ch[0]=='C')
        {
            scanf(
"%d",&n1);
            
int tmp =find_set(n1);
            printf(
"%d\n",nr[n1]);
        }
    }
    
return 0;
}

原文地址:https://www.cnblogs.com/lvpengms/p/1662792.html