题目链接:https://www.luogu.com.cn/problem/P1182
解题思路:
二分答案。
check(num)用于判断每段不超过num的情况是否存在。
然后二分答案。
实现代码如下:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n, m, a[maxn], sum;
bool check(int num) {
int cnt = 1, tot = 0;
for (int i = 0; i < n; i ++) {
if (tot + a[i] <= num) tot += a[i];
else if (a[i] > num) return false;
else {
tot = a[i];
cnt ++;
if (cnt > m) return false;
}
}
return true;
}
int main() {
cin >> n >> m;
int L = 0, R = 0, res;
for (int i = 0; i < n; i ++) {
cin >> a[i];
R += a[i];
}
while (L <= R) {
int mid = (L + R) / 2;
if (check(mid)) {
res = mid;
R = mid - 1;
}
else L = mid + 1;
}
cout << res << endl;
return 0;
}