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
题意:
题意大概就是几头牛排排站,统一面朝右(如下图),但是每头牛的身高不同,设Ci为奶牛i可见发型的奶牛数,请计算C1到Cn的总和。也就是求奶牛i能比右边多少个奶牛高,但有遮挡作用,即加入奶牛1身高为7 奶牛2身高为8 奶牛3身高为2 ,那么奶牛2挡住了奶牛1,奶牛1则看不到奶牛3。

思路:
这个题考察的是单调栈的知识。
关于栈的简单知识点:
stack<int> sta;
将x入栈:sta.push(x);
出栈:sta.pop();
判断栈的大小: sta.size();
判断栈是否为空:sta.empty();



样例的结果计算:
第一次:先将10入栈
第二次:3与10比较,10大于3,不需要pop出10,此时栈内元素只有一个(10),再将3入栈
第三次:7与栈顶元素3比较,3小于7,pop出3,10与7比较,10大于7,不需pop ,此时栈内元素只有一个(10),再将7入栈
第四次:4与7比较,4小于7,不需pop,此时栈内元素有两个(10,7),再将4入栈
第五次:12与4比较,4小于12,pop出4,同理,pop出7,10,此时栈内为空,元素为0个,再将12入栈
第六次:2与12比较,2小于12,不需pop,栈内有1个元素(12),2入栈
所以最终结果为:1+1+2+0+1=5
大概思路
按照顺序依次入栈,当栈内的元素小于等于即将入栈的元素,则pop掉,计算当前栈内元素的数量,然后再将即将入栈的元素入栈,最后将每一次计算的栈内元素的数量加起来即为所求结果
代码:
#include<stdio.h>
#include<stack>
#include<string.h>
#include<algorithm>
using namespace std;
stack<long long int>q;
int main()
{
int n;
scanf("%d",&n);
long long m,s=0;
scanf("%lld",&m);
q.push(m);
for(int i=1; i<n; i++)
{
scanf("%lld",&m);
while(q.size()&&q.top()<=m)//当栈不为空且栈顶元素小于等于m
q.pop();
s+=q.size();//删除比m小的数后计算栈的大小然后再将m入栈
q.push(m);
}
printf("%lld\n",s);
return 0;
}
本文介绍如何利用单调栈解决农场主约翰的问题,计算每头奶牛能看到其他奶牛发型的数目。通过逐个比较身高并维护栈中不超过当前奶牛高度的元素,计算最终可见牛的累计计数。
3854

被折叠的 条评论
为什么被折叠?



