The Blocks Problem 题解

The Blocks Problem

题目传送门 UVA - 101

刷刘大爷紫书的第二天

大致思路

这道题的大致思路应该比较明显,对每根柱子上的木块进行归位和转移两种操作
我的想法是用map存每个木块的在哪跟柱子上,再进行查找,归位和移动的操作

不过要主题原文的一句话
Any command in which a = b or in which a and b are in the same stack of blocks is an illegal
command…

因为没注意到这句话我这题WA了四发,程序重写了两次

#include <bits/stdc++.h>
using namespace std;
map<int,int>book;
vector<int>pile[30];
string s1="move",s2="pile",s3="onto",s4="over",s5="quit";
int find_block(int num){
    int p=book[num];
    for (int i = 0; i < pile[p].size(); ++i) {
        if(pile[p][i]==num)
            return i;
    }
}
void clear_block(int num){
    int p=find_block(num);
    int q=book[num];
    for (int i = pile[q].size()-1; i >=p ; --i) {
        int l=pile[q][i];
        book[l]=l;
        pile[l].push_back(l);
        pile[q].pop_back();
    }
}
void move_block(int x,int y){
    int p=find_block(x);
    int q1=book[x];
    int q2=book[y];
    for (int i = p; i <pile[q1].size() ; ++i) {
        int l=pile[q1][i];
        book[l]=q2;
        pile[q2].push_back(l);
    }
    pile[q1].erase(pile[q1].begin()+p,pile[q1].end());
}
int main(){
    int a,b,n;
    cin>>n;
    for(int i=0;i<n;i++) {
        book[i] = i;
        pile[i].push_back(i);
    }
    string x,y;
    while(cin >>x && x != s5){
        cin>>a>>y>>b;
        if(book[a]==book[b])
            continue;
        if(x==s1){
            if(y==s3){
                clear_block(a);
                clear_block(b);
                move_block(a,b);
            }
            else{
                clear_block(a);
                move_block(a,b);
            }
        }
        else{
            if(y==s3){
                clear_block(b);
                move_block(a,b);
            }
            else{
                move_block(a,b);
            }
        }
    }
    for (int i = 0; i < n; ++i) {
        cout<<i<<":";
        for (int j = 0; j < pile[i].size(); ++j) {
            cout<<" "<<pile[i][j];
        }
        cout<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/tlyzxc/article/details/105279169