【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
【Sample Output】
5
【Hint】
输入解释:
六头牛排成一排,高度依次是 10, 3, 7, 4, 12, 2。
3+0+1+0+1=5
【Source】
Silver
【Solution】
单调栈。每次统计能看到第i头牛的有多少个,同时将栈中小于等于它的高度的删除,因为它们会被第i头牛挡住。总个数即为所求答案。
代码如下:
/**************************************************************
Problem: 1660
User: llgyc
Language: Pascal
Result: Accepted
Time:176 ms
Memory:540 kb
****************************************************************/
const maxn = 80000+5;
var n,i,h,top:longint;
ans:int64;
stack:array[0..maxn] of longint;
begin
readln(n); fillchar(stack,sizeof(stack),0); stack[0]:=maxlongint; top:=0;
for i:=1 to n do begin
readln(h); while (h>=stack[top]) do dec(top);
inc(ans,top); inc(top); stack[top]:=h;
end;
writeln(ans);
end.