牛客小米 最优分割 经典二分最小化最大值
题目描述
依次给出n个正整数A1,A2,… ,An,将这n个数分割成m段,每一段内的所有数的和记为这一段的权重, m段权重的最大值记为本次分割的权重。问所有分割方案中分割权重的最小值是多少?
输入描述:
第一行依次给出正整数n,m,单空格切分;(n <= 10000, m <= 10000, m <= n)
第二行依次给出n个正整数单空格切分A1,A2,… ,An (Ai <= 10000)
输出描述:
分割权重的最小值
示例1
输入
复制
5 3
1 4 2 3 5
输出
复制
5
说明
分割成 1 4 | 2 3 | 5 的时候,3段的权重都是5,得到分割权重的最小值。
很老的二分题了
二分答案,check函数
判断是否可以分割成m
个
如果mid
分割个数cnt
大于m
说明猜mid
小了,可以向右边扩大一点
#ifdef debug
#include <time.h>
#include "/home/majiao/mb.h"
#endif
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>
#define MAXN ((int)1e5+7)
#define ll long long
#define int long long
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)
using namespace std;
#define show(x...) \ do { \ cout << "\033[31;1m " << #x << " -> "; \ err(x); \ } while (0)
void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
namespace FastIO{
char print_f[105];
void read() {}
void print() { putchar('\n'); }
template <typename T, typename... T2>
inline void read(T &x, T2 &... oth) {
x = 0;
char ch = getchar();
ll f = 1;
while (!isdigit(ch)) {
if (ch == '-') f *= -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
x *= f;
read(oth...);
}
template <typename T, typename... T2>
inline void print(T x, T2... oth) {
ll p3=-1;
if(x<0) putchar('-'), x=-x;
do{
print_f[++p3] = x%10 + 48;
} while(x/=10);
while(p3>=0) putchar(print_f[p3--]);
putchar(' ');
print(oth...);
}
} // namespace FastIO
using FastIO::print;
using FastIO::read;
int n, m, Q, K, a[MAXN];
int check(int mid) {
int sum = 0, cnt = 1;
for(int i=1; i<=n; i++) {
if(sum + a[i] <= mid) sum += a[i];
else {
cnt ++;
sum = a[i];
}
}
// show(cnt, m, mid);
return cnt > m;
}
signed main() {
#ifdef debug
freopen("test", "r", stdin);
clock_t stime = clock();
#endif
scanf("%lld %lld ", &n, &m);
int lef = 1, rig = 1, mid;
//左边界忘记初始化为max(a[i])导致WA65
for(int i=1; i<=n; i++)
scanf("%lld ", a+i), rig += a[i], lef = max(lef, a[i]);
while(lef < rig) {
mid = (lef + rig) >> 1;
int ret = check(mid);
// show(mid, ret);
if(ret) {
lef = mid + 1;
} else {
rig = mid;
}
}
printf("%lld\n", lef);
#ifdef debug
clock_t etime = clock();
printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif
return 0;
}