Description
Farmer John is an astounding accounting wizard and has realized he might run out of money to run the farm. He has already calculated and recorded the exact amount of money (1 ≤ moneyi ≤ 10,000) that he will need to spend each day over the next N (1 ≤ N ≤ 100,000) days.
FJ wants to create a budget for a sequential set of exactly M (1 ≤ M ≤ N) fiscal periods called “fajomonths”. Each of these fajomonths contains a set of 1 or more consecutive days. Every day is contained in exactly one fajomonth.
FJ’s goal is to arrange the fajomonths so as to minimize the expenses of the fajomonth with the highest spending and thus determine his monthly spending limit.
Input
Line 1: Two space-separated integers: N and M
Lines 2.. N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day
Output
Line 1: The smallest possible monthly limit Farmer John can afford to live with.
Sample Input
7 5
100
400
300
100
500
101
400
Sample Output
500
给出农夫在N天中每天的花费,要求把N天分成M组,使得各组的花费之和尽量小,最后输出最后输出各组花费之和中的最大值。
这题的纯粹是用二分来做枚举操作,枚举的上界是所有花费之和,下界为N天中其中花费最大的一天的值。
检查最大值为x时是否能满足的思路是这样的:把每天的花费扫描一遍,一边扫描一遍存入当前组,每当填满了这一组就继续往下一组里面填。如果所有的花费都填满了就可以满足,如果所有组都被填满了,花费的天数还有剩余的话就不能满足。
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int INF = 0x3f3f3f3f;
int a[100010];
int N,M;
bool check(int x)
{
int lower = 1;
for(int i = 1;i<=M;i++)
{
int sum = 0;
while(lower < N+1 && sum+a[lower]<=x )
{
sum +=a[lower];
lower++;
}
if (lower == N+1) return true;
}
return false;
}
int main()
{
// freopen("in.txt","r",stdin);
int sumA = 0;
int maxA= -INF;
scanf("%d%d",&N,&M);
for(int i = 1; i <= N; i++)
{
scanf("%d",&a[i]);
sumA+=a[i];
maxA = max(maxA,a[i]);
}
int lb = maxA;
int ub = sumA;
int mid;
while( ub-lb > 0)
{
// printf("L:%d R:%d\n",lb,ub);
mid = (lb+ub)/2;
if(check(mid)) ub = mid-1;
else lb = mid+1;
}
printf("%d\n",lb);
return 0;
}