南邮-2024-入栈序列和出栈序列

来源:互联网 发布:手机淘宝开店好吗 编辑:程序博客网 时间:2024/05/21 12:30

                                 入栈序列和出栈序列

时间限制(普通/Java):1000MS/3000MS          运行内存限制:65536KByte
总提交:111            测试通过:25

描述

给出入栈序列{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.

输出

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

样例输入


2 1 9 4 6 5

样例输出

9 6 5 4 1 2

提示

null

题目来源

NUPT

代码:#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
stack<int >S;
int CalculateTheMaxElementIndex(int *a,int a_length,int index); //计算从index开始知道数组结束最大元素的 下标并返回
int main()
{
int n;
    cin>>n;
int *a = new int[n];
int *b = new int[n];
for(int i = 0; i < n; i++)
cin >> a[i];
int tmp = 0;
int b_length = 0;
while(tmp < n)
{
int max = CalculateTheMaxElementIndex(a,n,tmp);    //就得最大值的下标
while(!S.empty())
{
if(S.top() > a[max])                            //让栈顶元素与最大值比,如果栈顶元素大,就把栈顶元素出栈并赋给b
{
b[b_length++] = S.top();
S.pop();
}
else
break;
}
b[b_length++] = a[max];                              //把求得的最大值赋给b
for(;tmp < max; tmp++)                               //让下标tmp和max之间的所有数入栈
S.push(a[tmp]);
tmp++;                                                //下次用当前max的下一个数开始
}
while(!S.empty())                                         //把栈里的所有元素出栈
{
b[b_length++] = S.top();
S.pop();
}
cout << b[0];
for(int i = 1; i < b_length; i++)
cout<< ' '<<b[i];
return 0;    
}
int CalculateTheMaxElementIndex(int *a,int a_length,int index)
{
    int i;
    int max = index;
    for(i=index+1;i<a_length;i++)
    {
        if(a[i] >a [max])
            max = i;
    }
    return max;
}  

0 0
原创粉丝点击