[BZOJ1660][Usaco2006 Nov]Bad Hair Day 乱发节

1660: [Usaco2006 Nov]Bad Hair Day 乱发节

Time Limit: 2 Sec  Memory Limit: 64 MB Submit: 1204  Solved: 589 [Submit][Status][Discuss]

Description

Input

* Line 1: 牛的数量 N。

 * Lines 2..N+1: 第 i+1 是一个整数,表示第i头牛的高度。

Output

* Line 1: 一个整数表示c[1] 至 c[N]的和。

Sample Input

6
10
3
7
4
12
2


输入解释:

六头牛排成一排,高度依次是 10, 3, 7, 4, 12, 2。

Sample Output

5

3+0+1+0+1=5
 
单调栈维护一个身高递减序列,注意是从n到1
#include <cstdio>
const int maxn = 80000 + 10;
int h[maxn], sta[maxn], top = 0;
int main(){
    int n;
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) scanf("%d", h + i);
    h[n + 1] = 1 << 30;
    sta[top = 1] = n + 1;
    long long ans = 0;
    for(int i = n; i; i--){
        while(top && h[i] > h[sta[top]]) top--;
        ans += sta[top] - i - 1;
        sta[++top] = i;
    }
    printf("%lld\n", ans);
    return 0;
}

 

posted @ 2017-09-07 19:32  Elder_Giang  阅读(126)  评论(0编辑  收藏  举报