棧(出棧序列)


已知自然數1,2,...,N(1≤N≤10000)依次入棧(即a<b當且僅當a先於b入棧),問:序列C1,C2,...,CN是否為可能的出棧序列。
  例如:N=5時,3,4,2,1,5是一個可能的出棧序列,因為其可以按如下操作獲得:push 1,push 2,push 3,pop,push 4,pop,pop,pop,push 5,pop

Input

 輸入數據包含若干組測試樣例。
  每組測試樣例的第一行為整數N(1≤N≤10000);
  第二行為N個正整數,以空格隔開,為出棧序列;
  輸入數據的末尾以一個0表示輸入的結束。

Output

對於每組測試樣例,輸出結果為一行字符串。
  如給出的序列是可能的出棧序列,則輸出"Yes",否則輸出"No"。
  注意:區分大小寫,引號本身不輸出。

Sample Input

5
3 4 2 1 5
5
3 5 1 4 2
0

Sample Output

Yes
No
#include<iostream>
#include<cstdio>
#include<stack>
#include<stdio.h>
using namespace std;
int main()
{
    stack<int> s;
    int a[10000]={0};
    int n,flag,i,j,top;
    while(1)
    {
        scanf("%d",&n);
        for(i=0;i<=n-1;++i)
            scanf("%d",&a[i]);
        if(n==0)
            return 0;
        flag=1;
        for(i=1;i<=a[0];++i)
            s.push(i);
        s.pop();
        for(j=1;j<=n-1;++j)
        {
            if(a[j]>a[j-1])
                for(i=a[j-1]+1;i<=a[j];++i)
                {
                    s.push(i);
                    s.pop();
                }
            else
            {
                top=s.top();
                if(top==a[j])
                    s.pop();
                else
                {
                    flag=0;
                    break;
                }
            }
        }
        if(flag==1)
            printf("Yes\n");
        else
            printf("No\n");
    }
    return 0;
}

 第二種方法

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <stack>
using namespace std;
int main()
{
    int N;
    while(scanf("%d",&N)!=EOF&&N)
    {
        stack <int> s1,s3;
        int s2[15000];
        int d=2,i,flag=0;
        for(i=1;i<=N;i++)
            scanf("%d",&s2[i]);
        for(i=N;i>=1;i--)
            s1.push(s2[i]);
        s3.push(1);
        while(1)
        {
            if(s3.top()==s1.top())
            {
                s1.pop();
                s3.pop();
            }
            if(s1.empty()&&s3.empty())
            {
                flag=1;
                break;
            }

            if(s3.empty())
                s3.push(d++);
            else if(s3.top()!=s1.top())
                s3.push(d++);
            if(d==N+2)
                    break;
        }
        if(flag)
            printf("Yes\n");
        else
            printf("No\n");
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM