1531 山峰 【栈的应用】

题目连接:http://codevs.cn/problem/1531/

题目描述 Description

Rocky山脉有n个山峰,一字排开,从西向东依次编号为1, 2, 3, ……, n。每个山峰的高度都是不一样的。编号为i的山峰高度为hi。

小修从西往东登山。每到一座山峰,她就回头观望自己走过的艰辛历程。在第i座山峰,她记录下自己回头能看到的山峰数si。

何谓“能看到”?如果在第i座山峰,存在j<k<i,hj<hk,那么第j座山峰就是不可见的。除了不可见的山峰,其余的山峰都是可见的。

回家之后,小修把所有的si加起来得到S作为她此次旅行快乐值。现在n座山峰的高度都提供给你了,你能计算出小修的快乐值吗?

输入描述 Input Description

第一行一个整数n(n<=15000)。

第i+1(1<=i<=n)行是一个整数hi(hi<=109)。

输出描述 Output Description

仅一行:快乐值。

样例输入 Sample Input

5

2

1

3

5

9

样例输出 Sample Output

5

数据范围及提示 Data Size & Hint

说明:s1=0, s2=1, s3=2, s4=1, s5=1。

分析:

只用维护当前单调递减的山峰序列即可

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<stack>
 5 using namespace std;
 6 int n,a[15050],ans,s[15009],top=1;
 7 int main()
 8 {
 9     scanf("%d",&n);
10     for(int i=1;i<=n;i++)
11         scanf("%d",&a[i]);
12     s[1]=a[1];
13     for(int i=2;i<=n;i++)
14     {
15         ans+=top;
16         if(s[top]>a[i]) s[++top]=a[i];
17         else {
18             while(s[top]<=a[i]&&top>=1) 
19             {
20                 top--;
21             }
22             s[++top]=a[i];
23         }
24     }
25     printf("%d",ans);
26     return 0;
27 }

代码来源:http://www.cnblogs.com/suishiguang/p/6216847.html

原文地址:https://www.cnblogs.com/huashanqingzhu/p/7704907.html