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 from1 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 strength of a group is the minimum height of the bear in that group.
Mike is a curious to know for each x such that1 ≤ x ≤ n the maximum strength among all groups of sizex.
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
很明显的数据结构题。一看到区间,还有个最小值,让我瞬间想到了线段树。
然而,这并没有什么卵用。因为每次查询之后我们还需要对每一个元素进行一次修改,使得它代表的是从它开始连续k个数的最小值。这样总的时间复杂度膨胀到了n * n * logn。为了处理高达二十万的数据我们可能要租用下天河二号。
仔细想一想,用了线段树真的高效了吗?如果我们不用线段树,每次都遍历整个表,然后遍历之后再对表中每个元素进行修改,充其量复杂度也就是2 * n * n(前面那个2只是为了强调一下。本质上时间复杂度肯定没有那个2的。。。)
我擦,上个线段树居然还tmd慢了!还不如线性的暴力快!对于这种数据范围,必须把复杂度压缩到n * logn才有戏,才能让评测机感到高兴。
想到这里:nlogn、最值、数据机构、线性。也许可以用单调栈来处理。
不知道单调栈的童鞋推荐去做下poj2559.只要你知道栈是什么鬼,再加上一点点思考就一定可以把那个题干掉的,从而对单调栈有一个清晰的认识。
对于每一个数据,如果我们都能知道他左右边第一个比他小的数的下标。那么这两个数之间所夹的区间中这个数不就是最小的吗?而且区间长度已知,咱们更新一下区间对应的最大值就完了。
However,这并不能完全解决问题。。。
凭什么认为每一个长度,从1到n都曾出现过呢?我们当然没有那个勇气说是。但是,我们可以轻松得到一个定理。假设len[i]表示的是长度为i的区间中符合题意的那个值,那么一定有len[i-1] >= len[i]。//此处多谢一位朋友指正。我下次会注意的。
所以为了防止蛋疼情况的出现,咱们从尾到头扫一遍就完了。至此问题得到了完美的解决。上代码:
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<stdlib.h>
#define INT_MAX 2147483647
#define N 200005
using namespace std;
int l[N],r[N];
int n;
int a[N];
int dp[N];
int main()
{
cin>>n;
for(int i = 1;i<=n;i++)
cin>>a[i];
a[0] = a[n + 1] = - INT_MAX;
for(int i = 1;i <=n ;i++)
{
int j = i - 1;
while(a[j] >= a[i]) j = l[j];
l[i] = j;
}
for(int i = n;i >= 1;i--)
{
int j = i + 1;
while(a[j] >= a[i])j = r[j];
r[i] = j;
}
for(int i = 1;i <= n;i++)
dp[r[i] - l[i] - 1] = max(dp[r[i] - l[i] - 1],a[i]);
for(int i = n - 1;i >= 1;i--)
dp[i] = max(dp[i + 1],dp[i]);
for(int i = 1;i <= n;i++)
cout<<dp[i]<<' ';
cout<<endl;
return 0;
}
建议这道题目的IO用C的而不是用C++的。数据量有一些大。如果用C++的速度慢了一些。虽然可以通过,但是这并不是什么好的习惯。