| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 24725 | Accepted: 9613 |
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
Lines 2.. N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day
Output
Sample Input
7 5 100 400 300 100 500 101 400
Sample Output
500
Hint
Source
题意:n个数字,不能打乱顺序,要求分成m组,使得这m部分中和的最大值最小。思路:最大值最小问题,二分答案即可。
# include <iostream>
# include <cstdio>
# include <algorithm>
# define INF 0x3f3f3f3f
# define MAXN 100000
using namespace std;
int n, m, sum, l, r, mid;
int a[MAXN+3];
bool ok(int mid)
{
int cnt = 0, sum = 0;
for(int i=0; i<n; ++i)
{
sum += a[i];
if(sum > mid)
{
++cnt;//记录已经分了几组。
sum = a[i];
}
}
return cnt+1 <= m;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
sum = 0;
int imax = -INF;
for(int i=0; i<n; ++i)
{
scanf("%d",&a[i]);
sum += a[i];
imax = max(imax, a[i]);//下界一定从数组的最大值开始。
}
l = imax, r = sum;
while(l<r)
{
mid = (l+r)>>1;
if(ok(mid))
r = mid;
else
l = mid + 1;
}
printf("%d\n",r);
}
return 0;
}
本文介绍了一个经典的预算划分问题,即如何将连续的每日开销数据合理地划分为多个区间(称为“fajomonth”),使得这些区间的最大总开销最小。通过二分查找的方法求解最优解。
1445

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



