• 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. 

    输入

    * 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.

    输出

    Print the output from each of the count operations in the same order as the input file.

    题目意思:把X那个整体搬到Y的那个整体上面 给出一个序号求其下面有多少块。
     
     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 int t;
     4 const int N=300005;
     5 int arr[N],sum[N],flood[N];
     6 
     7 int find_root(int x){
     8     if(x==arr[x]) return arr[x];
     9     int temp=arr[x];   //保存前面地根
    10     arr[x]=find_root(arr[x]); //递归先改变后面的
    11     flood[x]+=flood[temp];  //到根的距离
    12     return arr[x];
    13 }
    14 
    15 void union_set(int x,int y){
    16     int xx=find_root(x);
    17     int yy=find_root(y);
    18     arr[yy]=xx;
    19     flood[yy]=sum[xx];
    20     sum[xx]+=sum[yy];
    21 }
    22 
    23 int main()
    24 {
    25     ios::sync_with_stdio(false);
    26     cin>>t;
    27     string name;
    28     int d1,d2;
    29     for(int i=1;i<=300004;i++){
    30         arr[i]=i;
    31         sum[i]=1;
    32         flood[i]=0;
    33     }
    34     while(t--){
    35         cin>>name;
    36         if(name[0]=='M'){
    37             cin>>d1>>d2;
    38             union_set(d1,d2);
    39         }
    40         else{
    41             cin>>d1;
    42             int zhi=find_root(d1);
    43             cout << sum[zhi]-flood[d1]-1 << endl;
    44         }
    45     }
    46     return 0;
    47 }
    View Code
  • 相关阅读:
    Understanding Unix/Linux Programming-ls指令练习二
    Understanding Unix/Linux Programming-ls指令练习一
    Understanding Unix/Linux Programming-who指令练习
    复习自控有感——20160307
    根轨迹法的校正正目标、原理和方法
    Understanding Unix/Linux Programming-cp指令练习
    树莓派交叉编译环境在Linux下的建立
    Vue最全指令大集合————VUE
    JS实现动态瀑布流及放大切换图片效果(js案例)
    JS实现自动轮播图效果(js案例)
  • 原文地址:https://www.cnblogs.com/qq-1585047819/p/11193853.html
Copyright © 2020-2023  润新知