B. Mike and Feet
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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 × 10^5), the number of bears.
The second line contains n integers separated by space, a1, a2, …, an (1 ≤ ai ≤ 10^9), 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
題意:x從1到n,求長度x的這些子區間的最大值,每個區間的最大值定義爲該區間的最小值
解法:
- 求出每個值x向左和右以x爲最小值所能延伸的範圍width
- 然後貪心求解,對於位置site,它有兩個屬性,height和width,以height爲第一優先排序
- 每次從排序後的集合取最優先的值,如果他的width大與當前取的次數,那麼輸出這個height,否則重複當前步驟
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cassert>
using namespace std ;
const int N = 2e5 + 11 ;
struct Node {
int h , w ;
};
int tol[N] , tor[N] ;
int height[N] ;
Node arr[N] ;
bool cmp(const Node& a , const Node& b) {
if(a.h == b.h) return a.w > b.w ;
return a.h > b.h ;
}
int main() {
//freopen("data.in", "r" , stdin);
int n ;
while(scanf("%d" ,&n)==1) {
for(int i = 1 ; i <= n; ++i) scanf("%d" ,&height[i]) ;
tol[1] = 1 ; tor[n] = n ;
for(int i = 1 ; i <= n ; ++i) {
int tmp = i ;
while(tmp > 1 && height[tmp-1] >= height[i]) tmp = tol[tmp-1] ;
tol[i] = tmp ;
}
for(int i = n-1 ; i >= 1 ; --i) {
int tmp = i ;
while(tmp < n && height[tmp+1] >= height[i]) tmp = tor[tmp+1] ;
tor[i] = tmp ;
}
for(int i = 1 ; i <= n ; ++i) {
arr[i-1].w = (tor[i]-tol[i]+1) ;
arr[i-1].h = height[i] ;
}
sort(arr , arr+n , cmp) ;
int last = 0 ;
for(int i = 0 ; i < n ; ++i) {
if(arr[i].w > last) {
printf("%d" , arr[i].h) ;
++last ;
if(last == n) {printf("\n") ;break;}
else printf(" ") ;
--i ;
}
}
}
}