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
  • 相关阅读:
    面向对象编程的三大特征: 封装、继承、多态
    CDH和HDP对比
    mapreduce、spark、tez区别
    minio原理和使用
    HDP、CDH、CDP升级
    常用的分布式文件系统
    linux平台下防火墙iptables原理(转)
    php 1207
    php 1209
    php 1130
  • 原文地址:https://www.cnblogs.com/qq-1585047819/p/11193853.html
Copyright © 2011-2022 走看看