• POJ 3250 Bad Hair Day【单调栈】


    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 ≤ h≤ 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

    题意:牛i面向右看,当不比他高(包括等于)就是能看到,求这些牛能看到的和
    单调栈的题目,保存每头牛能看到 最右端的坐标

    代码如下:

    View Code
    #include<stdio.h> 
    #include<string.h>
    long long h[80005], right[80005];
    int main()
    {
        int i, j, k, n, temp;
        while(scanf("%d", &n)==1&&n)
        {
            memset(h, 0, sizeof(h));
            memset(right, 0, sizeof(right));
            for(i=1; i<=n; i++)
            {
                scanf("%lld", &h[i]);
                right[i]=i;
            }
            for(i=n-1; i>0; i--)
            {
                temp=i;
                while(h[temp+1]<h[i]&&temp<n) //想等也看不到 
                    temp=right[temp+1];
                right[i]=temp;
            }
            long long area=0; //这里验证过了...long long 是可以AC的 
            for(i=1; i<=n; i++)
                area+=(right[i]-i);
            printf("%lld\n", area);
        }
    }


  • 相关阅读:
    后缀表达式
    Linux中的硬链接和软链接
    C++中const总结
    atexit()函数
    Linux中的0号进程和1号进程
    什么是可重入函数和不可重入函数
    在线(Online)算法
    PHP验证IP地址输入的准确性:数组数值验证
    PHP网页计时工具——SESSION问题
    软件版本号命名规则
  • 原文地址:https://www.cnblogs.com/Hilda/p/2633673.html
Copyright © 2020-2023  润新知