POJ-3250-Bad Hair Day

本文介绍了一个使用单调栈解决的问题:给定一系列不同高度的奶牛,每个奶牛只能看到右侧比它矮的奶牛,文章提供了完整的代码实现,并解释了如何通过单调栈计算每个奶牛可以看到的奶牛数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:https://vjudge.net/problem/POJ-3250#author=Tiw_Air_OAO

题意:

给n个高度不同的奶牛,每个奶牛只能往右边看且比他矮的。

求每个奶牛能看到奶牛的和。

思路:

单调栈,每次加一个新牛,将比他矮的出栈,剩下的都是比他高的,表示他能被剩下的看到。

代码:

#include <iostream>
#include <memory.h>
#include <vector>
#include <map>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <queue>
#include <string>
#include <stack>

using namespace std;

typedef long long LL;

int main()
{
    int n, a;
    LL res = 0;
    stack<int> r;
    scanf("%d", &n);
    for (int i = 1;i <= n;i++)
    {
        cin >> a;
        while (!r.empty() && a >= r.top())
            r.pop();
        res += r.size();
        r.push(a);
    }
    printf("%lld\n", res);

    return 0;
}

  

转载于:https://www.cnblogs.com/YDDDD/p/10607044.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值