Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, …, N 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 M is 5 and N 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): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N 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:

  1. 5 7 5
  2. 1 2 3 4 5 6 7
  3. 3 2 1 7 5 6 4
  4. 7 6 5 4 3 2 1
  5. 5 6 4 3 7 2 1
  6. 1 7 6 5 4 3 2

Sample Output:

  1. YES
  2. NO
  3. NO
  4. YES
  5. NO

思路

在样例输入模拟一次栈的操作,我们可以发现失败的原因有两个:

  1. 元素在栈内,但不是栈顶;
  2. 栈不够长。

读入序列后,我们从左往右遍历序列:

  • 如果走到某个元素发现符合失败原因,就break
  • 如果能遍历完序列,说明能成功;

代码

  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4. int main() {
  5. int MAXLEN, NUM, K;
  6. cin >> MAXLEN >> NUM >> K;
  7. while(K--) {
  8. stack<int> myStack;
  9. int array[10001] = {0x0};
  10. // Read sequence
  11. for(int i = 0; i < NUM; i++)
  12. cin >> array[i];
  13. // Walk sequence
  14. int pos(0);
  15. int push_counter(0);
  16. for(pos = 0; pos < NUM; pos++) {
  17. // array[i] not in stack, do push operation
  18. if( array[pos] > push_counter ) {
  19. while( myStack.size() < MAXLEN && array[pos] > push_counter ) {
  20. myStack.push(push_counter+1);
  21. push_counter++;
  22. }
  23. }
  24. // Stack too short
  25. if( array[pos] > push_counter ) break;
  26. // array[pos] not equal top of stack
  27. if( array[pos] != myStack.top() ) break;
  28. myStack.pop();
  29. }
  30. if(pos == NUM) cout << "YES\n";
  31. else cout << "NO\n";
  32. }
  33. return 0;
  34. }