PTA(CCCC决赛模拟)----出栈序列的合法性 (25分)

你是我可爱的诱惑,温柔的牵绊,无法割舍的存在.你说青涩最搭初恋,我们有相遇的时间,在风暖月光的地点,海之角也不再遥远.你我之间,看不见的宣言,一直都在,重复过很多年.

给定一个最大容量为 M 的堆栈,将 N 个数字按 1, 2, 3, ..., N 的顺序入栈,允许按任何顺序出栈,则哪些数字序列是不可能得到的?例如给定 M=5、N=7,则我们有可能得到{ 1, 2, 3, 4, 5, 6, 7 },但不可能得到{ 3, 2, 1, 7, 5, 6, 4 }。

输入格式:

输入第一行给出 3 个不超过 1000 的正整数:M(堆栈最大容量)、N(入栈元素个数)、K(待检查的出栈序列个数)。最后 K 行,每行给出 N 个数字的出栈序列。所有同行数字以空格间隔。

输出格式:

对每一行出栈序列,如果其的确是有可能得到的合法序列,就在一行中输出YES,否则输出NO

输入样例:

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

输出样例:

YES
NO
NO
YES
NO

 

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <vector>
#include <ctime>
#include <cctype>
#include <bitset>
#include <utility>
#include <complex>
#include <iomanip>
#include <numeric>
#include<unordered_set>
#include <climits>//INT_100010n
#include <regex>
#include<deque>
//#include<bits/stdc++.h>
#define PP pair<ll,int>
#define inf 0x3f3f3f3f
#define INF 0x7fffffff
#define llinf 0x3f3f3f3f3f3f3f3fll
#define dinf 1000000000000.0
#define PI 3.1415926535898
#define wc 1e-18
typedef long long ll;
using namespace std;
priority_queue<int,vector<int>,less<int> > lp;
priority_queue<int,vector<int>,greater<int> >gp;
const ll mod=1e9+7;
using namespace std;
const int N=1e3+7;
stack <int> s;
int b[1010],t1,t2,m,n,k;
int main ()
{
    cin>>m>>n>>k;
    while (k--)
    {
        while (!s.empty())
            s.pop();
        t2=t1=1;
        int fg=1;
        for (int i=1; i<=n; i++)
            cin>>b[i];
        while(1)
        {
            if (t1==b[t2])
            {
                t1++;
                t2++;
            }
            else if(!s.empty()&&s.top()==b[t2])
            {
                s.pop();
                t2++;
            }
            else
            {
                if (t1>n)
                    break;
                s.push(t1);
                t1++;
                if (s.size()>=m)
                {
                    fg=0;
                    break;
                }
            }
        }
        if (!fg||!s.empty())
            cout<<"NO"<<endl;
        else
            cout<<"YES"<<endl;
    }
    return 0;
}

                                                                                                                   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值