原题链接:
题面:
题目描述
给你一个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出栈
解题思路:
如果栈顶的数比当前未入栈的数都大,则栈顶这个数该出栈了。
代码(CPP):
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e6 + 10;
const int INF = 0x3fffffff;
const int mod = 1000000007;
int n, a[maxn], Max[maxn];
stack<int> st;
void solve() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = n; i >= 1; i--) { // 预处理Max, Max[i]表示i右边最大的数(包括i)
Max[i] = max(Max[i + 1], a[i]);
}
bool first = true;
for (int i = 1; i <= n; i++) {
while (st.size() && st.top() > Max[i]) { // 在将a[i]入栈前,如果栈顶的数字大于后缀最大的,则出栈
int t = st.top();
st.pop();
if (!first)
cout << " ";
first = false;
cout << t;
}
st.push(a[i]); // a[i]入栈
}
while (st.size()) { // 把栈里边剩下的出栈
cout << " " << st.top();
st.pop();
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout << fixed;
cout.precision(18);
solve();
return 0;
}