題目大意:
輸入n,得到編号為0~n-1的木塊,分别擺放在順序排列編号為0~n-1的位置。現對這些木塊進行操作,操作分為四種。
1、move a onto b:把木塊a、b上的木塊放回各自的原位,再把a放到b上;
2、move a over b:把a上的木塊放回各自的原位,再把a發到含b的堆上;
3、pile a onto b:把b上的木塊放回各自的原位,再把a連同a上的木塊移到b上;
4、pile a over b:把a連同a上木塊移到含b的堆上。
當輸入quit時,結束操作并輸出0~n-1的位置上的木塊情況
Sample Input
10
move 9 onto 1
move 8 over 1
move 7 over 1
move 6 over 1
pile 8 over 6
pile 8 over 5
move 2 over 1
move 4 over 9
quit
Sample Output
0: 0
1: 1 9 2 4
2:
3: 3
4:
5: 5 8 7 6
6:
7:
8:
9:
思路:一個堆一個一維數組,整體二維數組(不定長數組使用STL中的vector來完成)
審題可發現move會将a上方的木塊歸位,onto會将b上方的木塊歸位
是以隻需要判斷move和onto将相應的歸位操作完成後,即可直接将(a及a以上的木塊)移到(b及b以上的木塊)之上
#include<iostream>
#include<cstdio>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
const int maxn = 25;
void start_block(int n);
void show_block();
void found_block(int a, int& p, int& h);
void clear(int p, int h);
void move(int a, int ha, int b);
int n;
vector<int> pile[maxn];
int main()
{
string s1, s2;
int a, b;
cin >> n;
start_block(n);
show_block();
while (cin >> s1&&s1 != "quit"&&cin >> a >> s2 >> b)
{
int pa, pb, ha, hb;
found_block(a, pa, ha);
found_block(b, pb, hb);
//if (s1 == "quit") break;
if (pa == pb) continue;
if (s1 == "move")clear(pa, ha);
if (s1 == "onto")clear(pb, hb);
move(pa, ha, pb);
}
show_block();
return 0;
}
void start_block(int n)//初始化木塊
{
for (int i = 0; i < n; i++)
{
pile[i].push_back(i);
}
}
void found_block(int a, int& p, int& h)//查找a木塊的位置,以引用的形式傳回調用者
{
for (p = 0; p < n; p++)
{
for (h = 0; h < pile[p].size(); h++)
if (pile[p][h] == a)return;
}
}
void show_block()
{
for (int i = 0; i < n; i++)
{
cout << i << ":";
for (int j = 0; j < pile[i].size(); j++)
{
cout << " " << pile[i][j];
}
cout << endl;
}
}
void clear(int p, int h) //将第p堆h高度以上的木塊歸位
{
for (int i = h + 1; i < pile[p].size(); i++)
{
int x = pile[p][i];
pile[x].push_back(x);
}
pile[p].resize(h + 1);
}
void move(int a, int ha, int b) //(a及a以上的木塊(b及b以上的木塊)之上
{
for (int i = ha; i < pile[a].size(); i++)
{
pile[b].push_back(pile[a][i]);
}
pile[a].resize(ha);
}
問題:
這裡第一次使用了cin當作while條件,以前一直用的是while(scanf)來判斷的
scanf作為傳回值是傳回的是正确接收的個數,而cin并不是如此
cin當作while循環條件的詳細測試将寫在下一篇部落格裡
不定長數組:vector
頭檔案
#include<vector>
vector<int> vec;
疊代器:
vector<int>::iteratorite ite = vec.begin();
vec.push_back(1);尾部添加
vec.pop_back(1);尾部删除
(vs裡增加已存在空間的一半)
vec.reserve(10);容量變大
vec.resize(3);重新設定有效原數個數
vec.empty();
vec.at(3);元素的引用
vec.back();最後一個元素
#include<algorithm>
vec.insert(vec.begin()+2,12); 添加元素
vec.clear();
vec.assign((vec.begin(),vec.end());
vec.erase(vec.begin(),vec.end());
vec.assign(2,5);
疊代器失效
算法:
#include<algorithm>
周遊:
for_each(vec.begin(),vec.end(),函數);
排序:
sort(vec.begin(),vec.end());
#include<functional>
sort(str.begin(),str.end(),greater<int>());從大到小
亂序:
random_shuffle(vec.begin(),vec.end());