您的位置:首页 > 其它

POJ 1208 The Blocks Problem 栈模拟 练STL

2013-07-28 16:02 465 查看
/**
*  栈模拟题: 拿来练STL的
*     第一次RE了,因为在move a的时候,a上方的block 只是pop了 但是没有push回原来的栈
*  也就是没有归位,而是单纯的出栈。
*     在判断命令的时候,其实只要分成两类,move 和 pile ,把这两命令视为cmd1
*  后面的 onto 和 over 视为cmd2。 先判断是 move 还是 pile,在判断是onto 还是 pile
*  也就是说当cmd1 同为 move或pile的时候,有一部分操作是相同的。
*     总的来说,POJ数据太水。 用了STL,还能0ms
*/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <algorithm>
#define INF 0x7fffffff
#define MAXS 26
#define LL long long
using namespace std;
char cmd1[5], cmd2[5], comands[5][5] = {{"move"}, {"pile"}, {"onto"}, {"over"}};
int num[MAXS], n;
vector<int> st[MAXS], temp;
void init() {
    temp.clear();
    for(int i = 0; i < n; i ++) {
        st[i].clear(); st[i].push_back(i);
        num[i] = i;
    }
}

void update(int a, int b) {
    if(!strcmp(cmd1, "move")) {
        while(!st[num[a]].empty() && st[num[a]].back() != a) {
            st[st[num[a]].back()].push_back(st[num[a]].back());
            num[st[num[a]].back()] = st[num[a]].back();
            st[num[a]].pop_back();
        }
        st[num[a]].pop_back();
        if(!strcmp(cmd2, "onto")) {
            while(!st[num[b]].empty() && st[num[b]].back() != b) {
                st[st[num[b]].back()].push_back(st[num[b]].back());
                num[st[num[b]].back()] = st[num[b]].back();
                st[num[b]].pop_back();
            }
        }
        st[num[b]].push_back(a);
        num[a] = num[b];
    } else {
        if(!strcmp(cmd2, "onto")) {
            while(!st[num[b]].empty() && st[num[b]].back() != b) {
                st[st[num[b]].back()].push_back(st[num[b]].back());
                num[st[num[b]].back()] = st[num[b]].back();
                st[num[b]].pop_back();
            }
        }
        while(!st[num[a]].empty() && st[num[a]].back() != a) {
            temp.push_back(st[num[a]].back());
            num[st[num[a]].back()] = num[b];
            st[num[a]].pop_back();
        }
        st[num[a]].pop_back();
        temp.push_back(a);
        num[a] = num[b];
        while(!temp.empty()) {
            st[num[b]].push_back(temp.back());
            temp.pop_back();
        }
    }
}

int main()
{
    vector<int> a;
    while(scanf("%d", &n) != EOF) {
        init();
        int a, b;
        while(scanf("%s", cmd1), strcmp(cmd1, "quit")) {
            scanf("%d%s%d", &a, cmd2, &b);
            if(num[a] != num[b])
                update(a, b);
        }
        for(int i = 0; i < n; i ++) {
            printf("%d:", i);
            for(vector<int>::iterator ite = st[i].begin(); ite != st[i].end(); ite ++) {
                printf(" %d", *ite);
            }
            printf("\n");
        }
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: