官方题解,学习单调栈了
For each i, find the largest j that aj < ai and show it by li (if there is no such j, then li = 0).
Also, find the smallest j that aj < ai and show it by ri (if there is no such j, then ri = n + 1).
This can be done in O(n) with a stack. Pseudo code of the first part (second part is also like that) :
stack s // initially empty
for i = 1 to n
while s is not empty and a[s.top()] >= a[i]
do s.pop()
if s is empty
then l[i] = 0
otherwise
l[i] = s.top()
s.push(i)
Consider that you are asked to print n integers, ans1, ans2, ..., ansn. Obviously, ans1 ≥ ans2 ≥ ... ≥ ansn.
For each i, we know that ai can be minimum element in groups of size 1, 2, ..., ri - li - 1.
Se we need a data structure for us to do this:
We have array ans1, ans2, ..., ansn and all its elements are initially equal to 0. Also, n queries. Each query gives x, val and want us to perform ans1 = max(ans1, val), ans2 = max(ans2, val), ..., ansx = max(ansx, val). We want the final array.
This can be done in O(n) with a maximum partial sum (keeping maximum instead of sum), read here for more information about partial sum.
Time complexity: .
#include <cstdio>
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
typedef long long ll;
#define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end(); ++it)
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 10;
int a[maxn],l[maxn],r[maxn],res[maxn];
int main(int argc, char const *argv[])
{
int n;
while(scanf("%d",&n)==1) {
for(int i = 1; i <= n; i++) scanf("%d",a+i);
stack<int>s;
for(int i = 1; i <= n; i++) {
res[i] = 0;
while(!s.empty()&&a[s.top()] >= a[i]) s.pop();
if(s.empty()) l[i] = 0;
else l[i] = s.top();
s.push(i);
}
while(!s.empty())s.pop();
for(int i = n; i >= 1; i--) {
while(!s.empty()&&a[s.top()] >= a[i]) s.pop();
if(s.empty()) r[i] = n + 1;
else r[i] = s.top();
s.push(i);
}
for(int i = 1; i <= n; i++) {
int x = r[i] - l[i] -1;
res[x] = max(res[x],a[i]);
}
for(int i = n-1; i > 0; i--) res[i] = max(res[i+1],res[i]);
for(int i = 1; i <= n; i++)printf("%d%c", res[i]," \n"[i==n]);
}
return 0;
}