题目链接
思路
$$ 二分 $$
时间复杂度
$$ O(Nlog(\sum_{i = 1}^Na_i)) $$
代码
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 1e5 + 10;
int n, m;
int a[MAXN];
bool check(int mid) {
int cnt = 0;
int cur = mid;
for (int i = 1; i <= n; i++) {
if (cur + a[i] > mid) {
cur = a[i];
cnt++;
if (a[i] > mid) {
return false;
}
} else {
cur += a[i];
}
}
return cnt <= m;
}
int main() {
scanf("%d%d", &n, &m);// don't forget &
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);// don't forget &
}
int l = 1, r = 1e9 + 10, ans = r;
while (l <= r) {
int mid = (l + r) >> 1;
if (check(mid)) {
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
printf("%d", ans);
return 0;
}