POJ 3273 Monthly Expense二分查找(最大值最小化问题)

题目:Monthly Expense

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 ≤ 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: 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.

思路:

1.先找出要二分的上下限,上限为所有天数花费的总和,下限为其中的最大话费,所要查找的最优解就在上限和下限之间

2.在上限下限之间进行二分,若得到的堆数大于题目所给的堆数,则应将mid+1赋值为下限,否则应将mid赋值为上限。

3.二分时得到堆数的判断,当总和大于mid时,堆数进行加一,而将总和重新进行赋值,否则总和一直相加,直到大于mid。

4.得到的下限或者上限即为最优解。

#include<stdio.h>
#include<iostream>
using namespace std;
int ans[100005];
int main()
{
int N,M;
scanf("%d%d",&N,&M);
int sum=0,MAX=0;
for(int i=0;i<N;i++)
{
scanf("%d",&ans[i]);
sum+=ans[i];
MAX=max(MAX,ans[i]);
}
while(MAX<sum)
{
int mid=(MAX+sum)/2;
int s=0,cnt=0;
for(int i=0;i<N;i++)
{
s+=ans[i];
if(s>mid)//此时的最优解为mid,因为MAX!=sum
//if(s>MAX)
{
cnt+=1;s=ans[i];
}
}
if(cnt<M) sum=mid;
else MAX=mid+1;
}
//跳出循环后 则MAX==sum
printf("%d\n",sum);
return 0;
}

最新文章

  1. 头显HTC Vive北美直降100美元,中国区降价活动今日公布
  2. 【Jquery】$.Deferred 对象
  3. mysql返回最后一列数据
  4. halcon读取一张照片,并转化为灰度图像
  5. centos 7.0 nginx 1.7.9 安装过程
  6. window svn链接
  7. 51nod 1135 原根
  8. bzoj 2878: [Noi2012]迷失游乐园
  9. C语言中的++和--
  10. 关于 ProcessEngines.getDefaultProcessEngine();NullPointException问题
  11. BeanUtils No value specified for Date的解决方法
  12. Teradata 的rank() 和 row_number() 函数
  13. C#中调用存储过程
  14. MySQL 基础(DDL)
  15. DataGridView绑定BindingList&lt;T&gt;带数据排序的类
  16. jdbc资料收集
  17. HDOJ 4607 - Park Visit
  18. curl continue
  19. 原生JS元素怎么取消事件
  20. 百度地图、高德地图、Google地图等坐标系相关梳理

热门文章

  1. PHP四种输出语句
  2. 18 react react-redux 的编写 TodoList
  3. 带你探索关于飞机Wi-Fi服务的神奇科学
  4. Tomcat跨域
  5. POJ 1019:Number Sequence 二分查找
  6. if case for while
  7. pinpoint 单机HBASE数据量过大问题解决
  8. 直击JDD | 京东技术全景图首次展示 四大重磅智能技术驱动产业未来!
  9. 干货|CVE-2019-11043: PHP-FPM在Nginx特定配置下任意代码执行漏洞分析
  10. 沙龙报名 | 京东云DevOps——自动化运维技术实践