Monthly Expense
Time Limit : 4000/2000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 64 Accepted Submission(s) : 19
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.
7 5 100 400 300 100 500 101 400
500
题意:题意为给定一个n个数组成的序列,划分为m个连续的区间,每个区间所有元素相加,得到m个和,m个和里面肯定有一个最大值,我们要求这个最大值尽可能的小。
思路:用二分查找可以很好的解决这个问题。这类问题的框架为,找出下界left和上界right, while(left< right), 求出mid,看这个mid值是符合题意,继续二分。最后right即为答案。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#include <iomanip>
#define maxn 15
#define mod 1000000007
#define inf 0x3f3f3f3f
#define exp 1e-6
#define pi acos(-1.0)
using namespace std;
int a[100010];
int main()
{
//ios::sync_with_stdio(false);
int n,m;
int i;
int minn=-inf;
int sum=0;
cin>>n>>m;
for(i=0;i<n;i++){ cin>>a[i]; if(minn<a[i]) minn=a[i];sum+=a[i]; }
int left=minn,right=sum,mid;
while(right-left>exp)
{
int cnt=0;
int sum1=0;
mid=(left+right)/2;
for(i=0;i<n;i++)
{
if(sum1+a[i]>mid){cnt++;sum1=a[i];}
else
{
sum1+=a[i];
}
}
cnt++; //注意此处最后一个花费的仍需要加一
if(cnt<=m) right=mid;
else left=mid+1;
}
cout<<right<<endl;
}