Codeforces 547B 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.

Sample test(s)
input
10
1 2 3 4 5 4 3 2 1 6
output
6 4 4 3 3 2 2 1 1 1

解題思路:單調隊列的典型應用,首先對於每一個元素a[i],我們求解出a[i]最左邊和最右邊能擴展到的位置,使得在這個區間內a[i]的值是最小的。其中l[i]和r[i]分別從頭到尾和從尾到頭利用單調隊列掃兩遍即可求出。這樣對於沒一個a[i]它能掌控的最大區間範圍我們便可以求解出,這樣我們便可以求解出部分ans[i],又因爲ans[i]隨着i的增大是單調不增的,我們需要n->1求解沒有更新的ans[i],即ans[i]=max(ans[i], ans[i+1]).

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <map>
#include <set>
#include <utility>
#include <algorithm>
#include <functional>
using namespace std;
const int maxn = 2*100010;
const int inf  = 0x3f3f3f3f;
deque< pair<int, int> > dq;
int a[maxn], l[maxn], r[maxn];
int ans[maxn];
int n;

int main() {

    //freopen("aa.in", "r", stdin);

    scanf("%d", &n);
    for(int i = 1; i <= n; ++i) {
        scanf("%d", &a[i]);
    }
    dq.push_back(make_pair(0, 0));
    for(int i = 1; i <= n; ++i) {
        while(dq.back().first >= a[i]) {
            dq.pop_back();
        }
        l[i] = dq.back().second + 1;
        dq.push_back(make_pair(a[i], i));
    }
    while(!dq.empty()) dq.pop_back();
    dq.push_back(make_pair(0, n + 1));
    for(int i = n; i >= 1; --i) {
        while(dq.back().first >= a[i]) dq.pop_back();
        r[i] = dq.back().second - 1;
        dq.push_back(make_pair(a[i], i));
    }
    memset(ans, 0, sizeof(ans));
    for(int i = 1; i <= n; ++i) {
        ans[r[i]-l[i]+1] = max(a[i], ans[r[i]-l[i]+1]);
    }
    for(int i = n - 1; i >= 1; --i) {
        ans[i] = max(ans[i], ans[i+1]);
    }
    printf("%d", ans[1]);
    for(int i = 2; i <= n; ++i) {
        printf(" %d", ans[i]);
    }
    printf("\n");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章