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 nextN (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.
InputLines 2.. N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day
7 5 100 400 300 100 500 101 400
500
题意:
一个农夫为了避免农场倒闭,开始计划支出。现在有N天,每天都必须支出Mi元,现在要求把这N天分成M个月(每个月中必须是连续的天数),让我们来安排月份,使得每个月支出的钱最少。
解题思路:
对结果进行二分,假设每月支出的钱为X,一天一天的减去支出,如果不足以减去下一天的支出,就说明得另起一个月,把月数记录下来,如果总月数小于M,则说明X可行,否则说明X不足以支出。如果找到和合适的X就继续找更大的,否则就找小的。
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
int a[100010];
int main()
{
int N,M;
//freopen("1.txt","r",stdin);
while(cin>>N>>M){
int maxs=0;int sum=0;
for(int i=0;i<N;i++){
cin>>a[i];sum+=a[i];
maxs=max(maxs,a[i]);
}
int high=sum,low=maxs,mid;//所求值定在high和low之间;
while(low<high){
int s=0,cou=0;mid=(low+high)>>1;
for(int i=0;i<N;i++){
s+=a[i];
if(s>mid){
cou++;s=a[i];
}
}
if(cou<M)high=mid;
else low=mid;
}
cout<<low<<endl;
}
}
这个题的思路现在都觉得在开飞机,完全没想到。其中利用M来分组也是特强,之前一直没想到如何去把N分成M组,而这里先确定值的范围,也就是high,low,然后得到mid,由mid去分组,然后看能否得到相应的分组数,并不断将此mid向最终的答案推进;