UVa 101 (模拟) The Blocks Problem

题意:

有n个木块及n个木块堆,初始状态是第i个木块在第i个木块堆上。对应有四种操作,然后输出最终状态。

分析:

用一个vector<int>模拟一个木块堆,进行相应操作即可。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <vector>
 4 #include <string>
 5 using namespace std;
 6 
 7 const int maxn = 30;
 8 int n;
 9 vector<int> pile[maxn];
10 
11 void find_block(int a, int& p, int& h)
12 {
13     for(int i = 0; i < n; ++i)
14         for(int j = 0; j < pile[i].size(); ++j)
15             if(pile[i][j] == a)
16             { p = i; h = j; }
17 }
18 
19 void clear_block(int p, int h)
20 {//将第p堆高度为h的上方的木块归位
21     for(int i = h+1; i < pile[p].size(); ++i)
22     {
23         int k = pile[p][i];
24         pile[k].push_back(k);
25     }
26     pile[p].resize(h+1);
27 }
28 
29 void move_onto(int pa, int h, int pb)
30 {//将pa堆高度为h及以上的木块摞到pb堆上
31     for(int i = h; i < pile[pa].size(); ++i)
32         pile[pb].push_back(pile[pa][i]);
33     pile[pa].resize(h);
34 }
35 
36 int main()
37 {
38     //freopen("in.txt", "r", stdin);
39     int a, b;
40     scanf("%d", &n);
41     for(int i = 0; i < n; ++i) pile[i].push_back(i);
42     string s1, s2;
43     while(cin >> s1 >> a >> s2 >> b)
44     {
45         int pa, pb, ha, hb;
46         find_block(a, pa, ha);
47         find_block(b, pb, hb);
48         if(pa == pb) continue;
49         if(s2 == "onto") clear_block(pb, hb);
50         if(s1 == "move") clear_block(pa, ha);
51         move_onto(pa, ha, pb);
52     }
53     for(int i = 0; i < n; ++i)
54     {
55         printf("%d:", i);
56         for(int j = 0; j < pile[i].size(); ++j) printf(" %d", pile[i][j]);
57         printf("
");
58     }
59 
60 
61     return 0;
62 }
代码君
原文地址:https://www.cnblogs.com/AOQNRMGYXLMV/p/4212491.html