題目大意:N個數,將其劃分成M部分,每一部分中的數的相對位置在原來的序列中不改變,意思是連續的,不能打亂順序隨意劃分,並將每一部分中的數相加,給出一系列數,求:這M個部分中最大的和最小爲多少。
這題就是最小化最大值,可以套用二分搜索模型,設C(X):=劃分中最大的和不大於X,至此用二分法搜索最小的X值。
#include <stdio.h>
#include <vector>
#include <math.h>
#include <string.h>
#include <string>
#include <iostream>
#include <queue>
#include <list>
#include <algorithm>
#include <stack>
#include <map>
#include<iostream>
#include<cstdio>
using namespace std;
int cost[100001];
bool CC(int x, int n, int m)
{
int curmonths = 1;
int curcost = 0;
for (int i = 0; i < n; i++)
{
if (cost[i] > x)
{
return false;
}
if (curcost + cost[i] <= x)
{
curcost += cost[i];
}
else
{
curcost = cost[i];
curmonths++;
}
if (curmonths > m)
{
return false;
}
}
return true;
}
int main()
{
#ifdef _DEBUG
freopen("d:\\in.txt", "r", stdin);
#endif
int n, m;
scanf("%d %d\n", &n, &m);
for (int i = 0; i < n;i++)
{
scanf("%d\n", &cost[i]);
}
int l = 0;
int r = n * 10000 + 1;
while (r - l > 1)
{
int mid = (r + l) / 2;
if (CC(mid, n, m))
{
r = mid;
}
else
l = mid;
}
printf("%d\n", r);
return 0;
}