POJ-3250(单调栈)
Some of Farmer John’s N cows (1 ≤ N ≤ 80,000) are having a bad hair day! Since each cow is self-conscious about her messy hairstyle, FJ wants to count the number of other cows that can see the top of other cows’ heads.
Each cow i has a specified height hi (1 ≤ hi ≤ 1,000,000,000) and is standing in a line of cows all facing east (to the right in our diagrams). Therefore, cow i can see the tops of the heads of cows in front of her (namely cows i+1, i+2, and so on), for as long as these cows are strictly shorter than cow i.
Consider this example:
=
= =
= - = Cows facing right -->
= = =
= - = = =
= = = = = =
1 2 3 4 5 6
Cow#1 can see the hairstyle of cows #2, 3, 4
Cow#2 can see no cow’s hairstyle
Cow#3 can see the hairstyle of cow #4
Cow#4 can see no cow’s hairstyle
Cow#5 can see the hairstyle of cow 6
Cow#6 can see no cows at all!
Let ci denote the number of cows whose hairstyle is visible from cow i; please compute the sum of c1 through cN.For this example, the desired is answer 3 + 0 + 1 + 0 + 1 + 0 = 5.
Input
Line 1: The number of cows, N.
Lines 2…N+1: Line i+1 contains a single integer that is the height of cow i.
Output
Line 1: A single integer that is the sum of c 1 through cN.
Sample Input
6
10
3
7
4
12
2
Sample Output
5
- 题目大意:
有站成一排站在一块的牛,每个牛只能往右看,然后只能看到比它矮的牛。要求求出每个牛能看到的牛的个数的和。
一个很裸的单调栈的题目,我们就通过这一个题来简单介绍一下单调栈。单调栈很明显就是一个要么递增要么递减的一个栈的数据结构,他可以用来解决左边(右边)第一个比它大(小)的数据的位置。具体如下:
1.维护从左往右递增栈可以得到左边第一个比a[i]小的元素位置L[i]。
2.维护从左往右递减栈可以得到左边第一个比a[i]大的元素位置L[i]。
3.维护从右往左递增栈可以得到右边第一个比a[i]小的元素位置R[i]。
4.维护从右往左递减栈可以得到右边第一个比a[i]大的元素位置R[i]。
那么具体是怎么实现的呢?核心代码如下:
for(int i=n;i>=1;i--)
{
while(s.size()&&a[s.top()]<a[i])
s.pop();
if(s.empty())
l[i]=n+1 ;
else
l[i]=s.top();
s.push(i);
}
这是维护了一个从右向左的一个单调递减的栈,用来求右边第一个比它大的位置,我们用l[]数组来记录,l[i]表示第一个比a[i]的数的位置,特别注意是位置!!!,每遇到一个数,我们用了
while(s.size()&&a[s.top()]<a[i]) s.pop();
这么一条语句来把栈中比a[i] 小的位置的都pop掉,又因为它是个单调的栈,所以s.top() 就是比a[i]大的第一个数的位置。
然后就是边界问题,如果栈空怎么办??那就是它后面没有比它大的数呀,那就赋值为n+1呗(为了后面便于计算)
完事之后还要把i入栈,要维护单调栈嘛。
针对这个题目来说,就是一个裸的单调栈,然后注意数组开成 long long 类型(因为h很大,超了int的范围了)的就ok了,完整代码如下:
#include <iostream>
#include <cstdio>
#include <stack>
#define ll long long
using namespace std;
const int maxn=800110;
ll a[maxn];
ll l[maxn];///第一个比l[i]表示第一个a[i]大的位置
int main()
{
stack<int>s;
ll n;
cin>>n;
while(s.size())
s.pop();
for(ll i=1;i<=n;i++)
cin>>a[i];
for(int i=n;i>=1;i--)
{
while(s.size()&&a[s.top()]<a[i])
s.pop();
if(s.empty())
l[i]=n+1 ;
else
l[i]=s.top();
s.push(i);
}
ll ans=0;
for(ll i=1;i<=n;i++)
{
ans=ans+(l[i]-i-1);
}
cout<<ans<<endl;
}