D. Mike and Feet(单调栈)

                                                                                    D. Mike and Feet

 

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 strength of 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.

Input

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.

Output

Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.

Examples

input

Copy

10
1 2 3 4 5 4 3 2 1 6

output

Copy

6 4 4 3 3 2 2 1 1 1 

题意:

给你一个数组,需要你找出长度从1到n的连续区间最小值的最大值,听起来有点绕,举个例子:让你在x == 1的条件下找到那个最大值,也就是列举数组中长度为一的连续的子集找到每个子集的最小值,求这些最小值中的最大值,即为所求。

思路:

我们可以反过来想,把数组里的每一个数都拿出来,计算出以其为最小值的最长连续区间,记该区间长度为len,那么这个数就确定是x从1~len的情况下的某个连续区间的最小值。如果创建一个数组ask来存放最终的答案,ask[i]代表x为i的时候所求的值,那么每计算出len之后就可以去更新ask数组中从1到len的值。

#include 
#include 
#include 
using namespace std;
const int N = 300000;
int a[N];
int ask[N];
int ll[N], rr[N];
struct node              //用来存放数组的元素与其对应的最大连续区间长度
{
    int num;
    int len;
}ans[N];

bool cmp(node a, node b)
{
    return a.num > b.num;
}

int main()
{
    int n;
    cin >> n;
    for(int i = 1; i <= n; i++)
    {
        cin >> a[i];
        ll[i] = i;
        rr[i] = i;
    }
    a[0] = a[n+1] = -1;
    for(int i = 2; i <= n; i++)             //三个for循环用来计算对应元素的len值,可以用其它的形式来求,不过可能会超时,亲身试过,感觉这种方法算是好的了
    {
        while(a[i] <= a[ll[i]-1])
        {
            ll[i] = ll[ll[i] - 1];
        }
    }
    for(int i = n - 1; i >= 1; i--)
    {
        while(a[i] <= a[rr[i] + 1])
        {
            rr[i] = rr[rr[i] + 1];
        }
    }
    for(int i = 1; i <= n; i++)
    {
        ans[i - 1].len = rr[i] - ll[i] + 1;
        ans[i - 1].num = a[i];
    }
    sort(ans, ans + n, cmp);        //不加排序在思路上是对的,不过会超时
    memset(ask, -1, sizeof(ask));
    ask[0] = 1e9;
    for(int i = 0; i < n; i++)
    {
        int len = ans[i].len;

        while(ask[len] < ans[i].num)         //更新数组
        {
            ask[len] = ans[i].num;
            len--;
        }
    }
    for(int i = 1; i <= n; i++)
    {
        if(i == 1)
          cout << ask[i];
        else
          cout << ' ' << ask[i];
    }

    return 0;
}

 

单调栈类型问题主要是用于解决一个以某个值为最小值的区间问题

你可能感兴趣的:(算法杂谈)