POJ 3250 Bad Hair Day【单调队列】

Description

Some of Farmer John'sNcows (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 cowihas a specified heighthi(1 ≤hi≤ 1,000,000,000) and is standing in a line of cows all facing east (to the right in our diagrams). Therefore, cowican see the tops of the heads of cows in front of her (namely cowsi+1,i+2, and so on), for as long as these cows are strictly shorter than cowi.

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!

Letcidenote the number of cows whose hairstyle is visible from cowi; please compute the sum ofc1throughcN.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: Linei+1 contains a single integer that is the height of cowi.

Output

Line 1: A single integer that is the sum ofc1throughcN.

Sample Input

6
10
3
7
4
12
2

Sample Output

5

分析:

这个题的实质是求从队列中任意一个数开始连续下降的数的个数的和。所以需要知道从队列中的某个数开始有多少个连续的下降的数。所以考虑使用单调队列。由于这道题不是求一个区间的最值,所以不用记录队首,队列退化为栈。而且没有区间长度限制,所以不用记录下标,也不用保留原数据,降低了空间复杂度。时间复杂度为O(n),注意sum的范围。
code:

 

View Code
#include<stdio.h>
int stack[80010];
int main()
{
int top=0,i,n,p;
__int64 sum=0;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&p);
while(top>0&&stack[top]<=p)
top--;
sum+=top;
stack[++top]=p;
}
printf("%I64d\n",sum);
return 0;
}


posted @ 2012-03-14 17:42  'wind  阅读(580)  评论(0编辑  收藏  举报