POJ-3250(單調棧)
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;
}