还是二分查找,不过这题注意最后要取upper bound的值为结果,还有这题用贪心的方法分组是对的吗?总感觉这样的分组不一定是最优的啊,但是最后竟然A了。。
#include<cstdio>
#include<algorithm>
using namespace std;
namespace
{
int N, M, dat[100000];
bool check(int limit)
{
int curr = 0, group = 0;
for (int i = 0; i < N; i++)
{
if (curr + dat[i] <= limit)
curr += dat[i];
else
{
curr = dat[i];
group++;
}
if (group > M)
return false;
}
return ++group <= M;
}
void solve(int lb, int ub)
{
int mid;
while (ub - lb > 1)
{
mid = (lb + ub) / 2;
if (check(mid))
ub = mid;
else
lb = mid;
}
printf("%d\n", ub);
}
}
int main()
{
scanf("%d %d", &N, &M);
int maxx = 0, sum = 0;
for (int i = 0; i < N; i++)
{
scanf("%d", &dat[i]);
maxx = max(dat[i], maxx);
sum += dat[i];
}
solve(maxx - 1, sum);
return 0;
}