Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high.
A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strengthof a group is the minimum height of the bear in that group.
Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x.
The first line of input contains integer n (1 ≤ n ≤ 2 × 105), the number of bears.
The second line contains n integers separated by space, a1, a2, ..., an (1 ≤ ai ≤ 109), heights of bears.
Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.
10 1 2 3 4 5 4 3 2 1 6
6 4 4 3 3 2 2 1 1 1
思路:
單調棧預處理,對於每一個數,以它爲最小值的最左的左下標L,最右的右下標R,然後更新答案ans[R-L+1]就好了,可以用單調棧搞定
/*======================================================
# Author: whai
# Last modified: 2015-12-09 13:39
# Filename: d.cpp
======================================================*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <set>
#include <map>
#include <queue>
#include <stack>
using namespace std;
#define LL __int64
#define PB push_back
#define P pair<int, int>
#define X first
#define Y second
const int N = 2 * 1e5 + 5;
int a[N];
int L[N], R[N];
P st[N];
int top = -1;
int ans[N];
void gao(int n) {
top = -1;
st[++top] = P(-1, 0);
for(int i = 1; i <= n; ++i) {
int j;
for(j = top; j >= 0; --j) {
if(a[i] >= st[j].X) break;
else R[st[j].Y] = i - 1;
}
if(a[i] > st[j].X) L[i] = st[j].Y + 1;
else L[i] = L[st[j].Y];
top = j;
st[++top] = P(a[i], i);
}
for(int i = 0; i <= top; ++i) {
R[st[i].Y] = n;
}
for(int i = 1; i <= n; ++i) {
//cout<<L[i]<<' '<<R[i]<<endl;
int u = R[i] - L[i] + 1;
ans[u] = max(ans[u], a[i]);
}
for(int i = n - 1; i > 0; --i) {
ans[i] = max(ans[i], ans[i + 1]);
}
for(int i = 1; i <= n; ++i) {
printf("%d ", ans[i]);
}
}
int main() {
int n;
while(cin>>n) {
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
}
gao(n);
}
return 0;
}