【例题1】数列分段
二分这个最大值,在 c h e c k check check 函数里面判断,如果该段的 s u m ≤ m i d sum \leq mid sum≤mid,不需要新的一段,否则需要,最后判断 c n t ≤ m cnt \leq m cnt≤m 是否成立。
#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[i−L] 取 min