zoukankan      html  css  js  c++  java
  • 2024-入栈序列和出栈序列

    #include<iostream>
    #include<algorithm>
    #include<queue>
    #include<stack>
    using namespace std;
    queue<int >Q;
    stack<int >S;
    int *p,n;
    int f(int a)
    {
        int i;
        int max=a;
        for(i=a;i<n;i++)
        {
            if(p[i]>p[max])
                max=i;
        }
        return max;
    }
    
    int main()
    {
    //    int n;
        cin>>n;
        p=new int [n];
        int *mark=new int [n];
        memset(mark,0,n*sizeof(mark[0]));
        int i;
        for(i=0;i<n;i++)
            cin>>p[i];
        int temp=-1;
        int k;
        while(temp!=n-1)
        {
            k=f(temp+1);
            while(!S.empty())
            {
            //    cout<<1;
                if(p[S.top()]>p[k])
                {
                    Q.push(p[S.top()]);
                    mark[S.top()]=1;
                    S.pop();
                }
                else
                    break;
            }
    
            mark[k]=1;
            Q.push(p[k]);
            for(i=temp+1;i<k;i++)
                S.push(i);
            temp=k;
        //    cout<<2<<endl;
        }
        for(i=n-1;i>=0;i--)
        {
            if(mark[i]==0)
                Q.push(p[i]);
        }
        for(i=0;i<n-1;i++)
        {
            cout<<Q.front()<<" ";
            Q.pop();
        }
        cout<<Q.front()<<endl;
    }  
    

      

    描述

     

    给出入栈序列{A},保证{A}各个元素值各不相等,输出字典序最大的出栈序列.

    如入栈序列{A} = 1, 2, 9, 4, 6, 5 则字典序最大的出栈序列为9, 6, 5, 4, 2, 1

    输入

    第一行一个整数n (1 <= n <= 100). 接下来是入栈序列{A}, n个正整数ai(0 < ai < 1000),且i != j则ai != aj.

    输出

    一行,字典序最大的出栈序列.   每个数字以空格分开。

    样例输入

    6

    2 1 9 4 6 5

    样例输出

    9 6 5 4 1 2

     

  • 相关阅读:
    阿里fastjson工具类
    poi导出excel2007版本
    java 利用poi 实现excel合并单元格后出现边框有的消失的解决方法
    spring整合atomikos实现分布式事务
    彻底理解ThreadLocal
    kubernetes架构和组件
    Promethues实战-简易教程系列
    Celery
    对称加密,非对称加密,证书机制
    Git diff
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3438692.html
Copyright © 2011-2022 走看看