Pop Sequence

来源:互联网 发布:合肥数码美工招聘信息 编辑:程序博客网 时间:2024/05/20 04:08
02-线性结构4 Pop Sequence(25 分)

Given a stack which can keep MMM numbers at most. Push NNN numbers in the order of 1, 2, 3, ..., NNN and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, ifMMM is 5 and NNN 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):MMM (the maximum capacity of the stack), NNN (the length of push sequence), and KKK (the number of pop sequences to be checked). Then KKK lines follow, each contains a pop sequence of NNN 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 51 2 3 4 5 6 73 2 1 7 5 6 47 6 5 4 3 2 15 6 4 3 7 2 11 7 6 5 4 3 2

Sample Output:

YESNONOYESNO
#include <iostream>#include<stack>#include<cmath>using namespace std;int M,N,K;stack<int>a;stack<int>s;string check(int *p){    if(p[0]>M)return "NO";    else    {        for(int i=1; i<p[0]; i++)        {            s.push(a.top());            a.pop();        }        a.pop();        for(int i=1; i<N; i++)        {            if(!s.empty()&&p[i]<s.top())            {                return "NO";            }            else if(!s.empty()&&p[i]==s.top())            {                s.pop();            }            else            {                int k=0,j=s.size();                while(!a.empty()&&p[i]>a.top())                {                    k++;                    if(k+j+1>M)return "NO";
                    s.push(a.top());                    a.pop();                }                if(a.empty())return "NO";                else                    a.pop();
            }        }        return "YES";    }}
int main(){    cin>>M>>N>>K;
    int *a1=new int [N];    for(int i=0; i<K; i++)    {        for(int j=0; j<N; j++)        {            cin>>a1[j];        }        while(!a.empty())a.pop();        for(int i=N;i>=1;i--){        a.push(i);    }    while(!s.empty()){        s.pop();    }
        cout<<check(a1)<<endl;    }
    return 0;}