题目:
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.
Lines 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天压缩为M个月,每个月包含连续的天数(数量任意)
,并给这些月份分配一个总支出限额(也就是这个月里的每天的支出之和不能超过的数),要求这个限额最小是多少。
思路:二分答案,注意对边界的计算。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,m;
int money[111111];
int maxm;
int judge(int x)
{
int counts,l,r;
counts=l=0;
r=1;
while(1)
{
int sum=money[l];
if(sum>x)
return 0;
while(r<n)
{
if(sum+money[r]<=x)
sum+=money[r++];
else
break;
}
l=r++;
counts++;
if(l==n)
{
if(counts<=m)
return 1;
else
return 0;
}
}
}
int bs(int l,int r)
{
int mid;
while(l<=r)
{
mid=(r-l)/2+l;
if(judge(mid))
r=mid-1;
else
l=mid+1;
}
return r+1;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
maxm=-1;
for(int i=0;i<n;i++)
{
scanf("%d",&money[i]);
maxm=max(maxm,money[i]);
}
int ans=bs(0,maxm*m);
printf("%d\n",ans);
}
return 0;
}
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int n,m;
int money[111111];
int maxm;
int judge(int x)
{
int counts,l,r;
counts=l=0;
r=1;
while(1)
{
int sum=money[l];
if(sum>x)
return 0;
while(r<n)
{
if(sum+money[r]<=x)
sum+=money[r++];
else
break;
}
l=r++;
counts++;
if(l==n)
{
if(counts<=m)
return 1;
else
return 0;
}
}
}
int bs(int l,int r)
{
int mid;
while(l<=r)
{
mid=(r-l)/2+l;
if(judge(mid))
r=mid-1;
else
l=mid+1;
}
return r+1;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
maxm=-1;
for(int i=0;i<n;i++)
{
scanf("%d",&money[i]);
maxm=max(maxm,money[i]);
}
int ans=bs(0,maxm*m);
printf("%d\n",ans);
}
return 0;
}