首页 > 代码库 > PAT 1051 Pop Sequence
PAT 1051 Pop Sequence
#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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。