二分的上下限初始值一定要是有意义的,不要随便给一个极小值和一个极大值
e.g. 对于 D - Minimum Width
ll = 0, r = 1e18
是一个错误的范围,没有考虑单个单词的长度
正确的上下限设定应该是,下限为单个单词的最长长度,上限为所有单词的长度之和(加上中间的空格)。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2e5+10;
LL n, m, l[N];
LL check(LL w)
{
LL lines = 1;
LL tmp = l[0];
for(int i = 1; i < n; ++i)
{
if(tmp + 1 + l[i] <= w)
{
tmp += (1 + l[i]);
}
else
{
tmp = l[i];
lines ++;
}
}
return lines;
}
int main()
{
cin >> n >> m;
LL ll = 0, r = 0;
for(int i = 0; i < n ; ++i)
{
cin >> l[i];
ll = max(ll, l[i]);
r += (l[i] + 1);
}
while(ll < r)
{
LL mid = ll + r >> 1;
if(check(mid) <= m)r = mid;
else ll = mid + 1;
}
cout << ll << endl;
return 0;
}