树不要皮,必死无疑;人不要脸,天下无敌|

Tx_Lcy

园龄:2年8个月粉丝:6关注:6

CF965D Single-use Stones

题目传送门

思路

这题的二分解法明明很简单,但是所有题解都是一样的做法,没有二分题解,于是我来一篇二分的题解。

容易想到若有 x 只青蛙时满足条件,x1 时也一定满足条件,于是这个函数就有了单调性,于是就可以二分。

接下来就是 check 函数了,我们使用一个双端队列 q 存放当前所有有青蛙的位置,若当前的位置上有石头,则我们可以弹出队首,若此时队首与当前位置的距离已经 >l,那么显然不满足条件,直接返回即可。

代码

#include<bits/stdc++.h> 
using namespace std;
#define int long long
int const N=1e5+10;
int a[N],w,l;
inline bool check(int x){
	deque< pair<int,int> >q;
	q.push_back({0,x});
	for (int i=1;i<w;++i){
		if (!a[i]) continue;
		if (abs(i-q.front().first)>l) return 0;
		int x=a[i];
		while (!q.empty() && x){
			auto now=q.front();q.pop_front();
			if (x>=now.second) x-=now.second;
			else{now.second-=x;x=0;q.push_front(now);}
		}
		q.push_back({i,a[i]-x});
	}
	return (w-q.front().first)<=l;
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	cin>>w>>l;
	for (int i=1;i<w;++i) cin>>a[i];
	int l=0,r=1e9;
	while (l<r){
		if (l+1==r){
			if (check(r)) l=r;
			break;
		}
		int mid=(l+r)>>1;
		if (check(mid)) l=mid;
		else r=mid-1;
	}
	cout<<l<<'\n';
	return 0;
}

本文作者:Tx_Lcy

本文链接:https://www.cnblogs.com/tx-lcy/p/16856755.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Tx_Lcy  阅读(22)  评论(2编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起