pat 1051Pop Sequence

模拟栈的过程,一开始我是用的cin来判断每行的每一个数字,然后判断回车结束。有一个点会超时,答案用数组先记录序列的方法非常好。有一个注意点就是访问s.top()的时候先要保证s。size()>0,这点和数组是一样的。

#include<bits/stdc++.h>
using namespace std;
int m,n,k;
int arr[1005];
int main()
{
    stack<int>st;
    scanf("%d %d %d", &m, &n, &k);
    int i;
    while (k--)
    {
        bool flag = true;
        int current = 1;
        for (i = 1; i <= n; i++)
        {
            scanf("%d", &arr[i]);
        } 
        while (!st.empty())
        {
            st.pop();
        }
        for (i = 1;i<=n; i++)
        {
            st.push(i);
            if (st.size()>m)
            {
                flag = false;
                break;
            }
            while (current <= n&&st.size()>0&&st.top() == arr[current])
            {
                st.pop();
                current++;
            }
        }
        if (st.size() == 0 && flag == true)
        {
            printf("YES\n");
        }
        else
            printf("NO\n");
    }
}

猜你喜欢

转载自www.cnblogs.com/legendcong/p/9644234.html