/**模拟题,难点在于看懂题目。。弄懂 move pile onto over 的意思就好办了*/
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
#define MAX_BLOCK 25
list<int> blocks[MAX_BLOCK]; //块堆
list<int>::iterator current_pos, goal_pos, tmp_current_pos, tmp_goal_pos; //被移动的块的位置和目标块的位置
int block_num, current, goal, current_block, goal_block; //块的总数、被移动块和目标块的编号、所在的块堆
void findCurrentAndGoal(){ //查找被移动块和目标块的块堆和在块堆中的位置
for(int i=0; i<block_num; i++){
tmp_current_pos = find(blocks[i].begin(), blocks[i].end(), current);
tmp_goal_pos = find(blocks[i].begin(), blocks[i].end(), goal);
if(tmp_current_pos!=blocks[i].end()) {current_block = i; current_pos = tmp_current_pos;}
if(tmp_goal_pos!=blocks[i].end()) {goal_block = i; goal_pos = tmp_goal_pos;}
}
}
void reset(int block, list<int>::iterator pos){ //重置块
pos++;
while(pos != blocks[block].end()){
blocks[*pos].push_front(*pos);
pos = blocks[block].erase(pos);
}
}
void moveBlock(string operate, string way){ //移动块
if(operate=="move"){
reset(current_block, current_pos);
if(way=="onto") reset(goal_block, goal_pos);
blocks[goal_block].push_back(*current_pos);
blocks[current_block].erase(current_pos);
}else{
if(way=="onto") reset(goal_block, goal_pos);
while(current_pos!=blocks[current_block].end()){
blocks[goal_block].push_back(*current_pos);
current_pos = blocks[current_block].erase(current_pos);
}
}
}
int main(int argc, char const *argv[])
{
string operate, way;
cin>>block_num;
for(int i=0; i<block_num; i++)
blocks[i].push_back(i);
while(cin>>operate,operate!="quit"){
cin>>current>>way>>goal;
findCurrentAndGoal();
if(current==goal || current_block==goal_block) continue;
moveBlock(operate, way);
}
for(int i=0; i<block_num; i++){
cout<<i<<':';
for(list<int>::iterator iter=blocks[i].begin(); iter!=blocks[i].end(); iter++){
cout<<' '<<*iter;
}
cout<<endl;
}
return 0;
}
uva_101 - The Blocks Problem
最新推荐文章于 2021-10-20 22:10:19 发布