Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 13327 | Accepted: 4494 |
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
Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i.
Output
Sample Input
6 10 3 7 4 12 2
Sample Output
5
题意很好理解就是一群牛从左到右站成一排,每头牛只能看见它右边的比它矮的牛的发型,若遇到一头高度大于或等于它的牛,则无法继续看到这头牛后面的其他牛了。
问的是每头牛能够看到牛的头数和。
问题就可以转化成每头牛被看到的次数和。
所以进而就可以想到用单调栈做这题了!
现将第一个高度入栈,然后后边每一个高度a与从栈顶元素开始依次向下比较,遇到比这个高度小的就弹出去(矮的牛看不到这头高a的牛)然以栈内剩下的元素个数就是能看到牛a的牛的头数,只是遍历一遍就可以将结果算出不会超时的~
上代码
#include <stdio.h>
#include <queue>
#include <string.h>
#include <stack>
using namespace std;
stack <__int64>sta;
int main(void)
{
__int64 n,num,count;
int i;
while(scanf("%I64d",&n)!=EOF)
{
count = 0;
scanf("%I64d",&num);
sta.push(num);
for(i = 1; i < n; i++)
{
scanf("%I64d",&num);
while(!sta.empty() && sta.top()<= num)
{
sta.pop();
}
count += sta.size();
sta.push(num);
}
printf("%I64d\n",count);
while(!sta.empty())
sta.pop();
}
return 0;
}
对今年网赛building那题深深地打击了。。立誓拿下单调栈!
啊啊啊单调栈我来了!