【bzoj1660】【单调栈】Bad Hair Day 乱发节

来源:互联网 发布:c语言for是什么意思 编辑:程序博客网 时间:2024/06/17 14:00

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

题解:维护一个单调递减栈,对于每一个元素,它对它之后的元素的贡献就是维护完栈之后栈里的元素个数。
#include<iostream>#include<cstdio>using namespace std;int n,top,a[80001],s[80001];long long ans;int main(){    scanf("%d",&n);    for(int i=1;i<=n;i++)       scanf("%d",&a[i]);    for(int i=1;i<=n;i++)    {        if(a[i]<s[top])            ans+=top;        else        {            while(a[i]>=s[top]&&top)                top--;            ans+=top;        }        s[++top]=a[i];    }    printf("%lld",ans);    return 0;}


0 0
原创粉丝点击