PAT:1051. Pop Sequence (25) AC

#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;

stack<int> str;      
int putin[1010];    //暂存查询的序列
int main()
{
  int m,n,k;        //栈容量m,栈序列1-n,查询k次
  scanf("%d%d%d",&m,&n,&k);
  while(k--)        //【skill】查询k次
  {
    while(!str.empty())  //清空栈,万一上一轮元素没有pop空,会受到上一次的影响。pop前必须判空!
      str.pop();
    memset(putin,0,sizeof(putin));
    for(int i=1 ; i<=n ; ++i)    //每次查询序列有n个数
    {
      scanf("%d",&putin[i]);
    }
    int index=1;    //指向查询序列待查位置
    bool ans=1;      //标记本序列是否合法
    for(int i=1 ; i<=n ; ++i)
    {
      str.push(i);  //进栈
      if(str.size()>m)
      {
        ans=0;    //失败1:栈爆了,标记不合法
        break;
      }
      while(!str.empty() && str.top()==putin[index])  //栈顶元素就是序列需求的数
      {              //【warning】“!str.empty()”不能另在下面写if判断,因为空的时候str.top()是无效的,会报错!
        str.pop();        //弹出这个数
        ++index;        //需求数为下一个
      }
    }
    if(!str.empty())    //【caution】失败2:全部都判断过居然没有输出完,肯定有问题。原因(序列里进出的数可能不是连号的)
      ans=0;
    if(1==ans)
      printf("YES
");
    else
      printf("NO
");
  }
  return 0;
}
原文地址:https://www.cnblogs.com/Evence/p/4319249.html