有n只熊。他们站成一排队伍,从左到右依次1到n编号。第i只熊的高度是ai。
一组熊指的队伍中连续的一个子段。组的大小就是熊的数目。而组的力量就是这一组熊中最小的高度。
迈克想知道对于所有的组大小为x(1 ≤ x ≤ n)的,最大力量是多少。
Input
单组测试数据。
第一行有一个整数n (1 ≤ n ≤ 2×10^5),表示熊的数目。
第二行包含n个整数以空格分开,a1, a2, ..., an (1 ≤ ai ≤ 10^9),表示熊的高度。
Output
在一行中输出n个整数,对于x从1到n,输出组大小为x的最大力量。
Input示例
10
1 2 3 4 5 4 3 2 1 6
Output示例
6 4 4 3 3 2 2 1 1 1
思路:
单调递增栈。找出一个区间的最小值占据的范围。
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
const int MAXN = 200005;
int a[MAXN], pos[MAXN], s[MAXN], top;
int result[MAXN];
int main()
{
int n, len;
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
}
memset(result, 0, sizeof(result));
a[n + 1] = -1;
top = 0;
for (int i = 1; i <= n + 1; i++)
{
if (top == 0 || a[i] > a[s[top - 1]])
{
s[top++] = i;
pos[i] = i;
continue;
}
else if (a[i] == a[s[top - 1]])
{
continue;
}
else
{
while (top >= 1 && a[i] < a[s[top - 1]])
{
--top;
len = i - pos[s[top]];
result[len] = max(result[len], a[s[top]]);
}
pos[i] = pos[s[top]];
s[top++] = i;
}
}
for (int i = n; i >= 1; i--)
{
result[i] = max(result[i], result[i + 1]);
}
for (int i = 1; i <= n; i++)
{
cout << result[i] << " ";
}
cout << endl;
return 0;
}