The Blocks Problem UVA 101 木块问题

本文介绍了一个使用 C++ 实现的堆操作模拟程序,能够处理木块堆叠的移动与清除指令,通过引用传递来更新堆状态,并最终打印出堆的状态。程序采用 vector 容器来模拟木块堆叠。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. #include<cstdio>
  2. #include<string>
  3. #include<vector>
  4. #include<iostream>
  5. using namespace std;
  6. const int maxn=30;
  7. int n;
  8. vector<int>p[maxn];

  9. void query(int &a1,int &h1,int a){             //用于找到输入值a,b所在的位置,并通过引用返回
  10.     for(a1=0;a1<n;a1++){
  11.         for(h1=0;h1<p[a1].size();h1++){
  12.             if(a==p[a1][h1])return ;
  13.         }
  14.     }
  15. }

  16. void clear1(int where,int height){               //清除 指定堆高度为height的木块上方全部移回原位
  17.     for(int i=height+1;i<p[where].size();i++){
  18.         int temp=p[where][i];
  19.         p[temp].push_back(temp);
  20.     }
  21.     p[where].resize(height+1);                   //此处注意,vector容器与数组相似,最大下标为长度减1;(这里只应保留下标为0~n的元素
  22. }

  23. void move(int w_a,int ha,int w_b){              //用于移动第a堆到第b堆上
  24.     for(int i=ha;i<p[w_a].size();i++){
  25.         int temp=p[w_a][i];
  26.          p[w_b].push_back(temp);
  27.     }
  28.     p[w_a].resize(ha);                         //最后第a堆元素因该为n- 1个;
  29. }

  30. void print1(){
  31.     for(int i=0;i<n;i++){
  32.     printf("%d:",i);
  33.     for(int j=0;j<p[i].size();j++){
  34.         printf(" %d",p[i][j]);
  35.     }
  36.     printf("\n");
  37.     }
  38. }
  39. int main(){
  40.     scanf("%d",&n);
  41.     for(int i=0;i<=n-1;i++)p[i].push_back(i);
  42.     int a,b;
  43.     string s1,s2;
  44.     while(cin>>s1>>a>>s2>>b){
  45.         if(s1=="quit")break;
  46.         int wa,wb,ha,hb;
  47.         query(wa,ha,a);
  48.         query(wb,hb,b);
  49.         if(wa==wb)continue;
  50.         if(s1=="move")clear1(wa,ha);
  51.         if(s2=="onto")clear1(wb,hb);
  52.         move(wa,ha,wb);
  53.     }
  54.     print1();
  55.     return 0;
  56. }