YbtOJ「基础算法」第3章 二分算法

YbtOJ 大全

【例题1】数列分段

二分这个最大值,在 c h e c k check check 函数里面判断,如果该段的 s u m ≤ m i d sum \leq mid summid,不需要新的一段,否则需要,最后判断 c n t ≤ m cnt \leq m cntm 是否成立。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#define re register
#define drep(a,b,c) for(re int a(b) ; a>=(c) ; --a)
#define rep(a,b,c) 	for(re int a(b) ; a<=(c) ; ++a)
using namespace std;
inline int read(){
   
	int x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){
   if(ch == '-') f=-1 ; ch=getchar();}
	while(ch>='0'&&ch<='9'){
   x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
	return x*f;
}
const int M = 1e5+10;
int n,m;
int a[M];
int l,r,sum; 
inline bool check(int x){
   
	int res = 0,cnt = 1;
	rep(i,1,n){
   
		if(res + a[i] <= x) res += a[i];
		else res = a[i],cnt++;
	}
	return cnt <= m;
}
signed main(){
   
	n = read(),m = read();
	rep(i,1,n) a[i] = read(),l = max(l,a[i]),r += a[i];
	while(l < r){
   
		int mid = (l+r)>>1;
		if(check(mid)) r = mid;
		else l = mid+1;
	}
	printf("%d\n",l);
	return 0;
}

【例题2】防具布置

考虑二分一个位置,如果该位置和前面的防具恰好是奇数个,该位置 − 1 -1 1 和前面的防具正好是偶数个,说明该位置有奇数个防具。最后输出类似于一个前缀和操作,该点的值减去前一个点的值。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#define re register
#define int long long 
#define drep(a,b,c) for(re int a(b) ; a>=(c) ; --a)
#define rep(a,b,c) 	for(re int a(b) ; a<=(c) ; ++a)
using namespace std;
inline int read(){
   
	int x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){
   if(ch == '-') f=-1 ; ch=getchar();}
	while(ch>='0'&&ch<='9'){
   x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
	return x*f;
}
const int M = 2e5+10;
int T,n,sum;
struct node{
   
	int s,e,d;
	node() {
    s = e = d = 0; }
}a[M];
inline int check(int x){
   
	int res = 0;
	rep(i,1,n) if(a[i].s <= x) res += (min(x,a[i].e) - a[i].s)/a[i].d + 1;
	return res;
}
inline void work(){
   
	n = read();
	sum = 0;
	rep(i,1,n){
   
		scanf("%lld%lld%lld",&a[i].s,&a[i].e,&a[i].d);
		sum += (a[i].e-a[i].s)/a[i].d + 1;
	}
	if(sum % 2 == 0) {
    printf("There's no weakness.\n"); return; }
	int l = 0,r = 2147483647;
	while(l < r){
   
		int mid = (l+r)>>1;
		if(check(mid) & 1) r = mid;
		else l = mid+1;
	}
	printf("%lld %lld\n",l,check(l) - check(l-1));
}
signed main(){
   
	T = read();
	while(T--) work();
	return 0;
}

【例题3】最大均值

要求平均数最大,我们二分这个平均数,并且把数组里的每一个值都减去这个平均数,问题就转化为了是否存在一个长度 ≥ L \geq L L 的连续子段,子段和非负。

子串和转化为前缀和相减,可以用一个变量记录当前的最小值,每次与新的取值 s u m [ i − L ] sum[i-L] sum[iL] min

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值