您的位置:首页 > 其它

木块问题(The Blocks Problem, UVa 101)

2017-07-22 19:47 351 查看
我用了迭代器

// uva101.cpp
#include <vector>
#include <iostream>
#include <string>
using namespace std;
const int MAX = 30;
vector<int> pile[MAX];
vector<int> tmp;
int n;
int find(int a){
for(int b = 0; b < n; b++)
for(vector<int>::iterator yy = pile[b].begin(); yy != pile[b].end(); yy++)
if (*yy == a) return b;
return -1;
}
void return_pile(int a){
int xx = find(a);
while(pile[xx].back() != a){
pile[ pile[xx].back() ].push_back( pile[xx].back() );
pile[xx].pop_back();
}
}

void pile_over(int a, int b) {
int pa = find(a);
int pb = find(b);
tmp.clear();
while(true) {
tmp.push_back( pile[pa].back() );
pile[pa].pop_back();
if (tmp.back() == a) break;
}
while(!tmp.empty() ){
pile[pb].push_back( tmp.back() );
tmp.pop_back();
}
}
void pile_onto(int a, int b){
return_pile(b);
pile_over(a, b);
}
void move_onto(int a, int b){
return_pile(a);
return_pile(b);
pile_over(a, b);
}
void move_over(int a, int b){
return_pile(a);
pile_over(a, b);
}
void print_pile(int n){
for(int b = 0; b < n; b++){
cout << b << ":";
for (vector<int>::iterator i = pile[b].begin(); i != pile[b].end(); ++i)
{
cout << " " << *i;
}
cout << endl;
}
}

int main(){
ios::sync_with_stdio(false);
cin >> n;
for (int i = 0; i < n ; i++){
pile[i].clear();
}
for(int i = 0; i < n; i++){
pile[i].push_back(i);
}
string cmd1, cmd2;
while((cin >> cmd1) && cmd1 != "quit"){
int a, b;
cin >> a >> cmd2 >> b;
int pa = find(a), pb = find(b);
if (pa == pb) continue;  // a, b can not be in the same pile
if(cmd1 == "move") {
if (cmd2 == "onto") move_onto(a, b);
else move_over(a, b);
}
else{
if (cmd2 == "onto") pile_onto(a, b);
else pile_over(a, b);
}
}
print_pile(n);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva