思路
贪心+模拟
如果栈顶比后面所有的数字都大,那么一定要弹出去,不然最后结果一定不是最大的(会被比他小的数字压到后面)。
所以我们就不断的去模拟这个操作就好了
首先维护一个后缀最大值数组q[i] 表示原数组[i-n)里最大的数字
然后遍历整个数组,依次入栈
6 7 8 3 7
第一步发现8比后面的数字都大所以弹出
第二步发现7(i==1)也大于等于后面数字最大值 所以弹出
最后依次弹出7 3 6
最后结果8 7 7 3 6
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 1000000;
const ll Mod = 1000000009;
int r[N + 5], q[N + 5];
bool cmp(int a, int b)
{
return a > b;
}
int main()
{
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
int n;
bool flag = 1;
stack<int> s;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> r[i];
}
for (int i = n-1; i >= 0; i--)
{
q[i] = max(r[i], q[i+1]);
}
for (int i = 0; i < n; i++)
{
s.push(r[i]);
while (!s.empty() && s.top()>= q[i + 1])
{
if (flag)
{
cout << s.top();
flag = 0;
}
else
cout << " " << s.top();
s.pop();
}
}
}
京公网安备 11010502036488号