Monthly Expense
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 38425 | Accepted: 14165 |
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
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.
Source
题目大意
Farmer John是一个令人惊讶的会计学天才,他已经明白了他可能会花光他的钱,这些钱本来是要维持农场每个月的正常运转的。他已经计算了他以后N(1<=N<=100,000)个工作日中每一天的花费moneyi(1<=moneyi<=10,000),他想要为他连续的M(1<=M<=N)个被叫做“清算月”的结帐时期做一个预算,每一个“清算月”包含一个工作日或更多连续的工作日,每一个工作日都仅被包含在一个“清算月”当中。 FJ的目标是安排这些“清算月”,使得每个清算月的花费中最大的那个花费达到最小,从而来决定他的月度支出限制。
对样例的理解
100 400 300 100 500 101 400 每天花费
---1--- ---2--- -3- -4- -5- 月度标号
500 400 500 101 400 月度花费
解析
这是一道最大化最小值的题目,要对n天的花费记录进行分组(分成m组)
主要的处理思想和上一道给牛建房子的思路相同
代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
const int maxn = 1e5+10;
using namespace std;
int n,m;
int a[maxn];
int ans=0;
int check(int md){
int cnt=1,sum=0;
for(int i=1;i<=n;i++){
//md存放的是每次二分的结果,如果说sum在加入数组值的过程中,小于等于mid(边界),那么就继续加
if(sum+a[i]<=md)
sum+=a[i];
else
{
//否则,另外建立一个分组
cnt++;
sum=a[i];
if(sum>md)
return 0;
}
}
return cnt<=m;
}
int main(){
//n天m组
scanf("%d %d",&n,&m);
int l=0,r=99999999;
int mid=-1;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
while(l<=r){
mid=(l+r)/2;
//cout<<mid<<endl;
if(check(mid))
r=mid-1,ans=mid;//用ans记录下最大化最小值
else
l=mid+1;
}
printf("%d\n",ans);
return 0;
}