PAT-A 真题- 1051. Pop Sequence

发布于 / PAT-甲级 / 0 条评论

题干:

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:

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

Sample Output:

YES
NO
NO
YES
NO

生词:

Sequence : 顺序,数列,使...排序            obtain : 获得,达到,存在

capacity : 容量,最大限度                          indeed : 确实,的确

题目大意:

有一个最大容量为M的栈,把1,2,3,4,5....n按照顺序依次入栈(以下用↓表示入栈),并给出出栈(以下用↑表示出栈)顺序,问顺序是否可能发生。

例如1 (↓) 1 (↑) 2 (↓) 2 (↑) 3 (↓) 3 (↑) 4 (↓) 4 (↑) 5 (↓) 5 (↑) 6 (↓) 6 (↑) 7 (↓) 7 (↑),所以1,2,3,4,5,6,7的顺序是可能的

然而1 (↓) 2 (↓) 3 (↓) 3 (↑) 2 (↑) 1 (↑) 4 (↓) 5 (↓) 6 (↓) 7 (↓) 7 (↑),此时出栈的结果是3,2,1,7,接下来栈顶是6,所以下一个出栈的只能是6,不可能是5,所以3 2 1 7 5 6 4这个顺序是不可能发生的。

测试数据会给出K组,对每一组进行判断。如果顺序可能发生则输出YES,反之输出NO

这个问题看上去很复杂,我们可以使用C++std模板库里面的stack进行模拟

C++:

#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;

int main(){
  int StackSize, icnt, cnt;
  cin >> StackSize >> icnt >> cnt;
  while(cnt--){  //对于每一行输入 
    queue<int> Q;
    stack<int> S;
    bool flag = true;
    for(int i = 0; i < icnt; i++){
      int n;
      cin >> n;
      Q.push(n);  //把输入元素压入队列 
    }
    for(int i = 1; i <= icnt; i++){
      S.push(i);  //把1-icnt依次压栈 
      if(S.size() > StackSize){  //超过栈的最大大小 
        flag = false; 
        break;  
      }
      while(S.size() && Q.size() && S.top() == Q.front())
        Q.pop(), S.pop();  //如果栈顶和队首相同,弹栈并出队 
    }
    //如果最后队列和栈都空了,而且中途没有超过最大大小,则输出yes 
    if(flag && S.empty() && Q.empty()) cout << "YES" << endl;
    else cout << "NO" << endl;
  }
  return 0;
}

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题- 1051. Pop Sequence
目前还没有评论,快来抢沙发吧~