Bad Hair Day---poj3250(栈的运用)

题目链接:http://poj.org/problem?id=3250

题意:
 n个牛排成一列向右看,牛i能看到牛j的头顶,当且仅当牛j在牛i的右边并且牛i与牛j之间的所有牛均比牛i矮。
 设牛i能看到的牛数为Ci,求∑Ci

本题正确解法是用栈来做的-----刚开始看的时候表示根本想不到栈

单调栈-----所谓单调栈也就是每次加入一个新元素时,把栈中小于等于这个值的元素弹出。
接下来回到这道题。求所有牛总共能看到多少牛,可以转化为:这n头牛共能被多少头牛看见。 当我们新加入一个高度值时,如果栈中存在元素小于新加入的高度值,那么这些小的牛肯定看不见这个高度的牛(那就看不见这头牛后边的所有牛),
所以就可以把这些元素弹出。每次加入新元素,并执行完弹出操作后,栈中元素个数便是可以看见这个牛的“牛数”~~~。
#include<stdio.h>
#include<stdio.h>
#include<algorithm>
#define N 1100
#include<stack>
#include<iostream>
using namespace std;
typedef long long LL;
int main()
{
    int n, x;

    while(scanf("%d", &n)!=EOF)
    {
        stack<int>sta;
        LL ans=0;
        scanf("%d", &x);
        sta.push(x);
        for(int i=2; i<=n; i++)
        {
            scanf("%d", &x);
            while(sta.size() && x>=sta.top())
                sta.pop();
            ans+=sta.size();
            sta.push(x);
        }
        printf("%lld
", ans);
    }
    return 0;
}

  

 
原文地址:https://www.cnblogs.com/zhengguiping--9876/p/4966779.html