(单调栈)Bad Hair Day

来源:互联网 发布:mysql innodb表修复 编辑:程序博客网 时间:2024/05/19 14:51

Bad Hair Day

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 2   Accepted Submission(s) : 1
Problem Description

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 ≤ h≤ 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 c1 through cN.
 

Sample Input
610374122
 

Sample Output
5
 

Source
PKU
 
思路分析:
使用"单调栈"。(从最后一头牛开始扫描(因为牛都往右看),并在最后的位置后面再虚拟一头hair无限高的牛,以方便处理。当处理完所有牛后便能得出最后答案)
痛的领悟:
答案要用long long类型,因为N最多取80000,而答案最多取N*(N+1)/2, 大于64亿。
<pre name="code" class="cpp">#include <cstdio>#include <algorithm>#include <math.h>#include <string.h>using namespace std;#define maxn 80005#define maxint 1000000005int h[maxn],s[maxn];int main(){int N, i;scanf("%d", &N);for (i = 0; i < N; i++)scanf("%d", &h[i]);int top = 0, base = 0;long long ans = 0;s[top++] = N;h[N] = maxint;//虚拟一头hair无限高的牛for (i = N - 1; i >= 0; i--){while (h[s[top - 1]] < h[i])//比当前牛的hair高度小的牛(编号)都出栈top--;ans += s[top - 1] - i-1;s[top++] = i;//只需要将牛的编号入栈便可得出答案}printf("%lld\n", ans);return 0;}


0 0
原创粉丝点击