DP/單調隊列::poj3250 Bad Hair Day

本文探讨了一种高效的方法来解决复杂问题,通过引入单调队列技术优化算法性能,详细解释了其工作原理和应用实例,展示了在特定场景下显著提高计算效率的可能性。

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

 

题目:

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 in our diagrams). Therefore, cowi 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 cowi.

Let ci denote the number of cows whose hairstyle is visible from cowi; please compute the sum ofc1 through cN.

分析:用DP去做,r[i]表示从右数第一个比a[i]大的数的前一个数的位置,则当a[i]<a[r[i]+1]时有r[i]=r[r[i]+1]. 求出了数组r[i]之后累加即可。一开始我把遍历的顺序弄错了,为for i=1..N,结果“Time Limit Exceeded”因为这里的DP根本不起作用,还是重复计算了!改了之后就对了,代码如下(Memory: 876K,Time: 641MS)

#include <iostream>
using namespace std;
unsigned long a[80001];
unsigned long r[80001];
unsigned long sum=0;

int main()
{
	int N;
	cin>>N;
	for(int i=1;i<=N;i++){
		cin>>a[i];
		r[i]=i;
	}
	for(int i=N-1;i>=0;i--){
		while(r[i]<N && a[r[i]+1]<a[i]){
			r[i]=r[r[i]+1];
		}
		sum+=r[i]-i;
	}

	cout<<sum;

	return 0;
}


 本题最好的方法还是用单调队列,因为上面DP的实现效率不是很高,也不容易分析。单调队列的话,其实和在hist中找最大矩形的方法一样的。这里不在重复。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值