1051 Pop Sequence (25分)

1 题目

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

时间限制: 400 ms
内存限制: 64 MB

2 思路

  • 题目大意:判断给出的出栈序列是否是合法
  • 分析(方法:模拟出栈)
    • 首先用数组存储出栈序列
    • 从1开始到n,逐个入栈,(开始判断之前清空栈,防止受上一个栈的数据影响)
      • 在每个元素入栈时候,判断是否超过规定的栈容量,如果超过则跳出循环,此序列非法
      • 同时,反复判断待出栈的元素是否等于栈顶元素,如果等于则出栈,并自增到下一个待出栈元素
    • 上述操作结束后,栈空(所有元素入栈后却不能全部出栈,肯定非法)且序列合法,则输出YES,否则输出NO

3 实现代码

//修改版
#include <cstdio>
#include <stack>

using std::stack;

#define MAX 1010 //序列的容量

bool Judge(int *arr, int n, int m){
    stack<int> st;

      while(!st.empty()){//下一个栈开始前,清空栈
      st.pop();
    }

    int current = 1;//栈序列中等待出栈的元素
    bool flag = true;//序列在栈中的容量是否合法

    for (int i = 1; i <= n; ++i)
    {
      st.push(i);

      if(st.size() > m){//如果入栈元素超过栈容量,则序列非法
          flag = false;
          break;
      }

      while(!st.empty() && st.top() == arr[current]){//如果栈顶元素等于当前出栈序列的元素,则出栈
          st.pop();
          current++;
      }

    }
      if(flag == true && st.empty() ==  true){//如果栈空,且序列在栈中的容量合法
      
      return true;
    }else{
      
      return false;
    }
}

int main(int argc, char const *argv[])
{

  int arr[MAX];
  int n, m, k;//栈的最大元素1~n,栈容m,k行
  scanf("%d%d%d", &m, &n, &k);

  while(k--){
    for (int i = 1; i <= n; ++i)//读入序列
    {
      scanf("%d", &arr[i]);
    }
    
    if(Judge(arr, n, m) == true){
      printf("YES\n");
    }else{
      printf("NO\n");
    }

  
  }

  return 0;
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页