Codeforces Round #305 B题 思维+贪心

来源:互联网 发布:cydia怎么卸载软件 编辑:程序博客网 时间:2024/05/17 22:11

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 ;            }        }    }}
0 0
原创粉丝点击