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
Hint
If Farmer John schedules the months so that the first two days are a month, the third and fourth are a month, and the last three are their own months, he spends at most $500 in any month. Any other method of scheduling gives a larger minimum monthly limit.
题意:
给出John在N个月中每个月的花费,John想将N个月分成M个组。
每组的月份是连续的,同一组的花费被相加起来,求所有分组情况中最高花费的最低值。
思路:
二分法,在【low,high】范围里面求,low是这个月花费最大值,high是这几个月花费之和。遍历各个月份,将花费总和不超过mid的月份归入一个组,统计在当前mid情况下能分成几个组。
如果组数小于M,说明mid偏大,范围变成前二分之一;
如果组数大于M, 说明mid偏小,范围变成后二分之一。
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<stack>
#include<map>
#include<queue>
typedef long long ll;
using namespace std;
const int N=1e6+10;
const int INF=0x3f3f3f3f3f;
int a[N],n,m;
int fie(int x)
{
int ans=0,sum=0;
for(int i=1; i<=n; i++)
{
if(ans+a[i]<=x)
{
ans+=a[i];
}
else
{
ans=a[i];
sum++;
}
}
if(sum>=m)
return 1;
else
return 0;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(a,0,sizeof(a));
int low=-99999;
int high=0;
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
high+=a[i];
if(low<a[i])
low=a[i];
}
while(low<=high)
{
int mid=(low+high)/2;
if(fie(mid))
low=mid+1;
else
high=mid-1;
}
printf("%d\n",low);
}
return 0;
}