码迷,mamicode.com
首页 > 其他好文 > 详细

PAT 1051 Pop Sequence

时间:2014-11-04 01:28:04      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   for   sp   div   on   log   

#include <cstdio>
#include <cstdlib>
#include <vector>

using namespace std;

bool push_validate(int &pre_push, int max_push, int cur, vector<int>& stack, int mcap) {
    if (pre_push >= max_push || pre_push >= cur) {
        // there not exist valid push for this pop
        return false;
    }
    if (cur > max_push) {
        // this pop value is out of range
        return false;
    }
    if (stack.size() + cur - pre_push > mcap) {
        // stack capacity not enough
        return false;
    }
    for (int j = pre_push+1; j<=cur; j++) {
        // push the value (if less value not pushed also push them in)
        stack.push_back(j);
    }
    pre_push = cur;
    return true;
}

bool validate(vector<int> &seq, int capacity) {
    int len = seq.size();
    int pre_push = 0;
    int max_push = len;
    
    vector<int> stack;
    int i = 0;
    while (i<len) {
        int cur = seq[i];
        //printf("cur seq: %d\n", cur);
        if (stack.empty() || cur != stack.back()) { // there must be a push before this pop or it‘s invalid
            if (push_validate(pre_push, max_push, cur, stack, capacity)) {
                continue;
            } else {
                return false;
            }
        }
        // easy case, just pop element from stack & check next in the pop seq
        i++;
        //printf("pop %d\n", stack.back());
        stack.pop_back();
    }
    return true;
}

int main() {
    int M, N, K;
    scanf("%d%d%d", &M, &N, &K);
    vector<int> seq(N);
    for (int i=0; i<K; i++) {
        for (int j=0; j<N; j++) {
            scanf("%d", &seq[j]);
        }
        
        if (validate(seq, M)) {
            printf("YES\n");
        } else {
            printf("NO\n");
        }
    }
    return 0;
}

以前考PAT时做过当时不知什么原因好像没全对,这回一次过

PAT 1051 Pop Sequence

标签:style   blog   io   color   for   sp   div   on   log   

原文地址:http://www.cnblogs.com/lailailai/p/4072614.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!