题目描述
给你一个1->n的排列和一个栈,入栈顺序给定
你要在不打乱入栈顺序的情况下,对数组进行从大到小排序
当无法完全排序时,请输出字典序最大的出栈序列
输入描述:
第一行一个数n 第二行n个数,表示入栈的顺序,用空格隔开,结尾无空格
输出描述:
输出一行n个数表示答案,用空格隔开,结尾无空格
示例1
输入
5 2 1 5 3 4
输出
5 4 3 1 2
说明
2入栈;1入栈;5入栈;5出栈;3入栈;4入栈;4出栈;3出栈;1出栈;2出栈
思路
用到了后缀最大值,因为栈的先进后出的,通过这个最大值去决定现在是否要出栈了,不出栈会不会使得字典序更小
代码
//栈和排序(模拟 贪心)
#include<stack>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e6 + 10;
int n , top;
int a[N] , maxe[N] , s[N];
int main()
{
scanf("%d" , &n);
for(int i = 0 ; i < n ; i++)
scanf("%d" , &a[i]);
for(int i = n - 1 ; i >= 0 ; i--)
maxe[i] = max(maxe[i + 1] , a[i]);//后缀最大值
for(int i = 0 ; i < n ; i++)
{
s[top++] = a[i];
while(top && s[top - 1] > maxe[i + 1])
printf("%d " , s[--top]);
}
return 0;
} 
京公网安备 11010502036488号