1051. Pop Sequence

来源:互联网 发布:oppe软件商店 编辑:程序博客网 时间:2024/06/09 22:14

题目:

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

基本思路

考察栈的基本操作。
根据题意,元素1~n 顺序入栈。对每一个待检查的出栈序列(存放在array[]中),令当前等待出栈的元素下标为now,初始值为1。入栈过程中,比较array[now]是否与栈顶元素相等,若相等则pop栈顶元素并使now后移一位。now++后只要栈顶元素仍然等于当前等待出栈的元素,则持续出栈。

注意点

1.设置bool型变量flag,若flag==true表示输出序列合法,反之;
2.一次判断结束后(即1~n都已经入栈完毕了),若栈st非空,说明当前待比较的出栈序列不合法。因为若是合法输出序列,在比较过程中栈st就会被pop完;
3.每次判断一个输出序列是否合法时,务必 要清空栈st。因为若前一次比较的输出序列不合法,那栈中会有元素残留;
4.输出栈顶元素st.pop()或pop()前一定要判断栈是否为空,否则很可能会出错。

代码
#include<cstdio>#include<stack>using namespace std;const int maxn = 1001;stack<int> st;//定义栈int main(){    int m,n,k;    int array[maxn];//待检查的出栈序列    scanf("%d%d%d",&m,&n,&k);//输入栈的最大容量,出栈序列的元素个数,待检查的序列数    while( k-- ){//k 次循环         while( !st.empty()){//在每次处理一个新的出栈序列前应做清空处理             st.pop();        }         for(int i=1;i<=n;i++){//输入待检查的出栈序列             scanf("%d",&array[i]);        }         int now = 1;//now 表示array[]中当前等待被输出元素的下标         bool flag = true;//flag==false 表示当前待检查的序列是非法输出序列         for(int i=1;i<=n;i++){//按顺序1,2,3...n 入栈            st.push(i);            if(st.size() > m){//爆栈                 flag = false;                break;            }else{                //若栈顶元素与出栈序列当前待输出的值相同(一定要先判空)                while( !st.empty() && st.top() == array[now]){                    st.pop();//反复弹出栈顶元素并令now++                    now++;                  }            }                }        if(st.empty() == false){//若在一遍for循环之后st扔非空,则表明当前待检查的出栈序列为不合法            flag = false;        }         if(flag == true) printf("YES\n");        else printf("NO\n");     }     return 0;} 
0 0
原创粉丝点击