Pop Sequence

来源:互联网 发布:网络知识安全竞赛入口 编辑:程序博客网 时间:2024/05/29 21:33

Given a stack which can keep MM numbers at most. Push NN numbers in the order of 1, 2, 3, ..., NN and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if MM is 5 and NN is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.

Input Specification:

Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): MM (the maximum capacity of the stack), NN (the length of push sequence), and KK (the number of pop sequences to be checked). Then KK lines follow, each contains a pop sequence of NN numbers. All the numbers in a line are separated by a space.

Output Specification:

For each pop sequence, print in one line "YES" if it is indeed a possible pop sequence of the stack, or "NO" if not.

Sample Input:

5 7 51 2 3 4 5 6 73 2 1 7 5 6 47 6 5 4 3 2 15 6 4 3 7 2 11 7 6 5 4 3 2

Sample Output:

YESNONOYESNO

先贴上自己的代码仍有(BUG),还是边界问题没考虑好。


#include <stdio.h>#include <vector>#include <stdlib.h>using namespace std;bool isTrue(int M, int N, int a[1001]);void Push(vector<int>& Stack, int i, int j);int main(){int M, N, K;scanf("%d %d %d", &M, &N, &K);int *v = (int *)malloc(sizeof(int)*N);int i;for (; K != 0; --K){for (i = 0; i != N; ++i)scanf("%d", v + i);if (isTrue(M, N, v))printf("YES\n");elseprintf("NO\n");}//system("pause");return 0;}void Push(vector<int>& Stack, int i, int j) {while (j > i) {i++;Stack.push_back(i);}}bool isTrue(int M, int N, int a[1001]){int max = 0;int popCount = 0;int pushCount = 0;vector<int> Stack;if (a[0] > M)return false;Push(Stack, 0, a[0]);max = a[0];popCount = 0;pushCount = 1;for (int j = 1; j < N; j++) {if (Stack.empty())//instead of tipsStack.push_back(0);if (a[j] > Stack.back()) {if (Stack.back() == 0)Stack.pop_back();if (pushCount == 1)Stack.pop_back();if (a[j] <= max)return false;Push(Stack, max, a[j]);pushCount = 1;if (Stack.size() > M)return false;popCount = 0;max = a[j];}else {while (a[j] <= Stack.back()) {pushCount = 0;Stack.pop_back();popCount++;if (popCount > M)return false;if (Stack.empty() && a[j] != 1)return false;else if (Stack.empty() && a[j] == 1)break;}}}}

以下是结合别人的代码自己重写的

#include <iostream>#include <stack>#include <cstdlib>using namespace std;int main(){stack<int> Stack;int M, N, K;int input, temp;bool flag;cin >> M >> N >> K;while (K--){temp = 1;flag = true;for (int i = 0; i < N; i++){cin >> input;while (Stack.size() <= M && flag){if (Stack.empty() || Stack.top() != input)//tipsStack.push(temp++);else if (Stack.top() == input){Stack.pop();break;}}if (Stack.size() > M)flag = false;}if (flag)cout << "YES" << endl;elsecout << "NO" << endl;while (!Stack.empty())Stack.pop();}system("pause");return 0;}
差距:

(1)边输入边处理,而不是将输入结果存入数组后再处理,节省了时间和空间。

(2)temp变量代替了我的max变量和一次次的比较。这点是因为我对题意理解不够。

(3)写注释的一行有一点小技巧,empty() || top(), 而不是我代码中注释的那一行。栈为空时直接判断出结果,不必再执行top。










0 0
原创粉丝点击