木块问题(UVa101)

  题目具体描述见:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=37

将操作分解为基本步骤,编写函数,重复调用

C++11代码如下:

 1 #include<iostream>
 2 #include<vector>
 3 #include<string>
 4 using namespace std;
 5 
 6 const int maxn =25;
 7 vector<int> pile[maxn];
 8 int n;
 9 void find_block(int a, int& p, int& h) {  //找到木块所在的位置和高度(从0开始)
10     for (p = 0; p < n; p++) {
11         for (h = 0; h < pile[p].size(); h++) {
12             if (pile[p][h] == a) return;
13         }
14     }
15 }
16 
17 void clear_above(int p, int h) {  //将p位置高度h以上的木块移回原位
18     for (int i = h + 1; i < pile[p].size(); i++) {
19         int b = pile[p][i];
20         pile[b].push_back(b);
21     }
22     pile[p].resize(h + 1);  //保留 0-h高度的木块
23 }
24 
25 void pile_onto(int p, int p2,int h) {   //将p位置处从h高度的木块全部移动到p2顶部
26     for (int i = h; i < pile[p].size(); i++) {
27         pile[p2].push_back(pile[p][i]);
28     }
29     pile[p].resize(h);  //保留高度0~h-1的木块
30 }
31 
32 void print() {  //输出全部操作介绍后各个位置木块的信息
33     for (int i = 0; i < n; i++) {
34         cout << i << ':';
35         for (int j = 0; j < pile[i].size(); j++)
36             cout << ' ' << pile[i][j];
37         cout << endl;
38     }
39 }
40 
41 int main() {
42     int ha, pa, hb, pb;
43     cin >> n;
44     for (int i = 0; i < n; i++) pile[i].push_back(i);
45     string s1, s2;
46     int a, b;
47     while (cin >> s1 >> a >> s2 >> b) {
48         find_block(a, pa, ha);
49         find_block(b, pb, hb);
50         if (pa == pb) continue;
51         if (s1 == "move") clear_above(pa, ha);
52         if (s2 == "onto") clear_above(pb, hb);
53         pile_onto(pa, pb, ha);
54     }
55     print();
56     return 0;
57 }

猜你喜欢

转载自www.cnblogs.com/pgzhang/p/9268631.html
今日推荐