POJ 3250 Bad Hair Day 解题报告(单调栈板子)

本文介绍了一种使用单调栈解决特定排列中元素可视数量的算法问题。通过从左到右遍历并维护一个单调递减的栈,可以有效地计算出每只牛能被左侧多少牛看到的总次数,从而得出所有牛可以看到的发型总数。

题目链接

题目大意

所有牛都有身高,两两身高可以相等,他们都朝着右边看,如果,牛 I 的高度,大于,牛 J(其中 I 在 J 的左侧),那么牛 I 可以看到牛 J 的头发。此时,给你一排牛的身高,问,全部牛可以看到的别的牛发型的总数。

题解

单调栈,由左到右入栈。我们直接统计每只牛可以被左边的牛看到的次数,这时候把这些次数加起来就是答案。
如果,入栈时候,有牛小于这只入栈的牛,那么这头牛出栈。确保了单调栈的内的牛,一定可以看到入栈的牛的发型。

为啥不统计一头牛能看到的多少牛的发型的数目?

栗子:10 2 7 4 3 2 1
显然,不行,因为不满足严格单调递减。

AC code

#include<iostream>
#include<queue>
#include<cstring>
#include<string>
#include<sstream>
#include<map>
#include<vector>
#include<cstdio>
#include<set>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<stack>
#include<ctime>
using namespace std;
#define rep(i,aa,bb) for(register int i=aa;i<=bb;i++)
#define rrep(i,aa,bb) for(register int i=aa;i>=bb;i--)
#define mset(var,val)	 memset(var,val,sizeof(var))
#define LL long long
#define eps 0.000001
#define inf 0x7f7f7f7f
#define llinf 1e18
#define exp 0.000001
#define pai 3.141592654
#define random(x)   rand()%(x)
#define lowbit(x)   x&(-x)
inline int read()
{
    int x=0,y=1;char a=getchar();while ( a>'9' || a<'0'){if ( a=='-')y=-1;a=getchar();}
    while ( a>='0' && a<='9' ){	x=(x<<3)+(x<<1)+a-'0'; a=getchar();}return x*y;
}
#define N 80004
int n;LL ans = 0 ;int hei[N];
int sta[N],tot = 0 ;
int main()
{
    n = read();
    for (int i = 1; i <= n; i++){
        int num = read();
        while ( tot && sta[tot] <= num )
            tot--;
        ans += tot;
        sta[++tot] = num;
    }
    printf("%lld\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值