zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    《剑指offer》第十二题(矩阵中的路径)
    《剑指offer》第十五题(二进制中1的个数)
    《剑指offer》第十题(斐波那契数列)
    《剑指offer》第十一题(旋转数组的最小数字)
    原始的生成对抗网络GAN
    《剑指offer》第九题(用两个栈实现队列)
    (转)c++一些知识点
    贪心算法
    动态规划——最长公共子串
    动态规划——主元素算法
  • 原文地址:https://www.cnblogs.com/qq-1585047819/p/11193853.html
Copyright © 2011-2022 走看看