POJ

来源:互联网 发布:金英杰网络课程价格 编辑:程序博客网 时间:2024/06/06 12:38
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 ≤ 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 c1 through cN.
Sample Input

6
10
3
7
4
12
2
Sample Output

5
Source

USACO 2006 November Silver


题意:有n只奶牛,分别告诉你他们的高度,让他们站成一排,从左往右看,只有左边的奶牛可以看到右边的奶牛(右边的奶牛看不到左边的),只有高的奶牛可以看到比它矮的奶牛,也就是说左边的较高的奶牛可以看到右边比他低的奶牛,问所有奶牛一共可以看到的奶牛之和是多少?

分析:首先要有一个转换的思想,如果先计算每只奶牛可以看到的奶牛数,再加起来,那么复杂度就是O(n^2),但是如果我们换一个idea,把求所有奶牛可以看到的其他奶牛之和转化为所有奶牛可以被多少头奶牛看到的数量之和.这两个问题是等价的,这样,整个问题就比较好解决了,复杂度也降低了很多(略大于O(n)),从左到右扫一遍奶牛的高度,用一个栈保存前i-1头奶牛中可以被第i头奶牛看到的数量,然后每次统计一下,计算和.

参考代码:

#include<cstdio>#include<cmath>#include<cstring>#include<algorithm>#include<stack>#include<iostream>using namespace std;typedef long long ll;const int maxn = 8e4+10;int n;int h[maxn];ll ans;int main(){while( ~scanf("%d",&n)){for( int i = 0; i < n; i++)scanf("%d",&h[i]);//要求每头牛可以看到的牛的数量之和//可以转化为每头牛可以被多少头牛看到的数量ans = 0;stack<int> s;for( int i = 0; i < n; i++){while( !s.empty() && s.top() <= h[i])s.pop();ans += s.size();s.push(h[i]);}printf("%lld\n",ans);}return 0;}



原创粉丝点击