Monthly Expense(最大化最小值问题)

来源:互联网 发布:光驱推荐知乎 编辑:程序博客网 时间:2024/06/06 13:15

点击打开链接

Problem 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 nextN (1 ≤ N ≤ 100,000) days.

FJ wants to create a budget for a sequential set of exactly M (1 ≤ MN) 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: <i>N</i> and <i>M</i>< br>Lines 2..<i>N</i>+1: Line <i>i</i>+1 contains the number of dollars Farmer John spends on the <i>i</i>th day

 


Output

Line 1: The smallest possible monthly limit Farmer John can afford to live with.

 


Sample Input

7 5100400300100500101400

 

Sample Output
500

题目大意:

给你n个点,让你分成c组(按顺序分组),求这c组的和,最小的是多少?

思路:

上界是n个数的和,也就是分成1组的情况,下界是n个数里面的最大值,也就是分成c组的情况,然后看mid = (r + l) / 2 能够把n个数分成多少组。

如果FJ安排他的月度预算,他将把前两天划分在一个月中,把第三天、第四天划分在一个月当中,最后的三个工作日各自在一个月当中,所以他一个月最多花费500元,其他的方法总是得出一个较大的结果。

(100 400) (300 100) (500) (101) (400)


别人的题解分析:(感觉对于求最大化最小值很有帮助)
最大化最小值或者最小化最大值的问题可以用二分法来做。为什么用二分?
以求最大化最小值问题为例。
我们知道二分有一个前提就是对有序的东西才能二分查找。也就是这个问题变量是有序的才能用二分。
在求最大化最小值时,既然求,那么这个值一定有一个范围。而求最大化最小值时。既然它可以“最大化”,那我们一般可以推到一个”最大值“。既然它可以“最小值”,那我们一般可以推到一个”最小值“。可知最终的这个“”一定在这个最大值与最小值之间的范围里。当我们在这个范围里挑一个值得时候。我们经过处理,得出一个和题目要求位置相同的变量。我们挑的这个值确定的这个变量状态与题目的要求变量进行比较。这个就是有序的。在本题中就是,但我枚举一个总和k后,求得在这个中和下的最大分段数,这个分段数与题目要求的分m段的比较是有序的。如果比m大,说明段数分多了–>说明k枚举小了,接下来再在大于k的区间枚举。这就可以二分了。

再就是唯一性问题。
一般而言最大化最小值问题都会只有一个确定的答案(如果有多个答案,也应该都是一样的值)这是显然的。那么在二分过程中我们应该是不断缩小[L,R]的范围,最终使得L==R才退出二分。这样才是一个唯一的结果。如果当我们过程中查到了某个值的状态满足题目要求就退出。我们就无法保证这是唯一的那个答案。   


//Monthly Expense#if 0#include<iostream>#include<cmath>  #include<algorithm>#include<cstring>#include<cstdio>using namespace std;int a[100005];//int b[50],k;int n,c;int fun(int mid) {//cout<<"*************************"<<endl;int cnt=0,sum=0;for(int i=0; i<n; i++){if(sum+a[i]<=mid){sum+=a[i];//b[k]=a[i];//k++;}else{//for(int i=0; i<k; i++)//cout<<b[i]<<"  ";//cout<<endl<<"&&&&&&&&&&"<<endl;//k=0;//memset(b,0,sizeof(b));sum=a[i];cnt++;}}if(cnt>=c)                   {return 1;}else{return 0;}}int main(){while(scanf("%d%d",&n,&c)==2) { int r=0,l=0,mid=0; memset(a,0,sizeof(a));for(int i=0; i<n; i++) {scanf("%d",&a[i]);r+=a[i];l=max(l,a[i]);}while((r>=l)){mid=(l+r)/2;     if(fun(mid))            //多了 {l=mid+1;}else{r=mid-1;}}cout<<l<<endl;}}#endif 












原创粉丝点击