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.
Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i.
6 10 3 7 4 12 2
5
题解:很基础的一个单调栈思想题,如样例,10,3,7,4,12,2.因为左边的牛i可以看到右边第一个大于等于他的牛j区间(I,J)中的所有牛,所以我们可以声明一个栈,维护从大到小的值。
.....................1.首先把10放进栈中。
......................2.看3,因为3<10,所以可以把3放入栈中。
......................3.看7,因为7>栈首元素3,所以把3从栈中pop,在弹出的时候,可以知道有多少头牛可以看到高度为3的牛的头呢?当然就是所有留在栈中的元素个数。
......................4.4可以直接入栈。
......................5.12大于栈首元素,所以不断弹栈,直到栈为空或者栈首元素大于当前值为止。
注意最后一个值操作完之后,栈不一定为空,此时的栈是一个元素单调递减的栈,所以里面满足的个数有(sz-1)*(sz)/2.
代码如下:
/*by kzl*/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
const int maxx = 80000+500;
const int INF = 0x3f3f3f3f;
typedef long long LL;
int c,n;
LL sum = 0;
stack<int>st;
int main(){
while(~scanf("%d",&n)){
sum = 0;
for(int i=0;i<n;i++){
scanf("%d",&c);
int num = 0;
while(!st.empty()&&st.top()<=c){
st.pop();
int sz = st.size();
sum+=sz;
}
st.push(c);
}
int sz = st.size();
sum+=(sz-1)*sz/2;
while(!st.empty())st.pop();
printf("%lld\n",sum);
}
return 0;
}