现在的位置: 首页 > 综合 > 正文

NYOJ练习题 how many hairstyles can they see?

2013年06月30日 ⁄ 综合 ⁄ 共 1543字 ⁄ 字号 评论关闭

how many hairstyles can they see?

时间限制:1000 ms  |  内存限制:65535 KB
描述

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). 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.

For example:

There are six cows, heights are 10  2  7  3  12  2.

Now 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!

输入
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.
输出
Line 1: A single integer that is the sum of c1 through cN.
样例输入
6
10  2  7  3  12  2
样例输出
5

题意:有n头牛面向右排队,每头牛只能看到右边比它矮的牛,右边比它高的牛会挡住视线;如果比它高的牛的右边还有比它矮的牛,它同样看不到那些牛。求这n头牛能看到的其他牛的数量的总和。

解法:使用栈。如果栈顶的数大于当前元素,说明栈顶的牛可以看见当前的牛,则把当前的元素压入栈中;否则,说明栈顶这头牛看不到当前位置之后的牛了,就可以计算出栈顶的牛可以看到的牛的个数,并让栈顶元素出栈,然后继续比较栈顶元素,直到栈顶元素大于当前位置,把当前元素压入栈中。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 8e4 + 10;
int sta[N], pos[N];
int main()
{
    int n, i, a;
    while(~scanf("%d",&n))
    {
        int top = 0;
        scanf("%d",&a);
        sta[++top] = a;
        pos[top] = 1;
        int ans = 0;
        for(i = 2; i <= n; i++)
        {
            scanf("%d",&a);
            while(top > 0 && sta[top] <= a)
            {
                ans += i - pos[top] - 1;  //求出的ans是top位置的牛能看到的牛的数量
                top--;
            }
            sta[++top] = a;
            pos[top] = i;
        }
        top--; //最后一头牛一头也看不到
        while(top > 0)
        {
            ans += n - pos[top];
            top--;
        }
        printf("%d\n",ans);
    }
    return 0;
}
/*当找到一个比栈顶元素大的数时,就让栈顶元素出栈,直到栈空,把当前元素压入栈中*/

抱歉!评论已关闭.