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.
题目的意思是让把n个数组成的序列划分为m段,每种划分方式都会有一段数字之和是这m段中最大的那一段,我们的任务就是确定一种划分方式使最大的那一段最小。
这种问题可以用二分查找解决,思路是找出上界right和下界left,while(left<right)求mid=(left+right)/2,再根据结果动态改变left或right的值,在本题中如果mid<=m说明上界太大了,就要让right=mid,如果mid>m说明下界太小了,要让left=mid+1,到最后当left==right的时候说明找到答案了。
下面是代码:
#include<iostream>
using namespace std;
int dat[100005];
int main()
{
int n,m;
int left=-1,right=0,mid,ci,sum;
cin>>n>>m;
for(int i=1;i<=n;++i)
{
cin>>dat[i];
if(left<dat[i]) left=dat[i];
right+=dat[i];
}
while(left<=right)
{
mid=(left+right)/2;
ci=0;
sum=0;
for(int i=1;i<=n;++i)
{
if(sum+dat[i]>mid)
{
sum=dat[i];
ci++;
}
else sum+=dat[i];
}
ci++;//千万别忘了加上最后一组!!!
if(ci<=m) right=mid-1;
else left=mid+1;
}
cout<<left<<endl;
return 0;
}
博客围绕将n个数组成的序列划分为m段,使最大段和最小的问题展开。介绍可用二分查找解决,思路是找出上下界,通过循环求中间值并动态改变上下界,直至找到答案,还给出了相关代码示例。
1445

被折叠的 条评论
为什么被折叠?



