POJ-3273-Monthly Expense-二分法

POJ-3273-Monthly Expense-二分法



Monthly Expense
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 18072 Accepted: 7238


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

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.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


题意:

将N个数分成M组,每组的值为该组所有数的和,求在所有分法中 “M组值的最大值” 最小是是多少


思路:

显然,我们可以很轻松的确定所求值ans(以下简称ans)的取值区间:ans要不小于N个数中的最大值,该最大值作为ans的下界;同时要不大于任意分法中的 “M组值的最大值”,则我们可选任意一种分法的“M组值的最大值”作为ans的上界。为方便计算,我选择将N个数中前N-M+1个的和作为ans的上界——对应分法“前N-M+1个一组,后面每个数一组”(当然,前N-M+1个的和可能会比后面M-1个数中的某一个小,这样的情况是包含于 “前N-M+1个的和小于N个数中的最大值” 中,而在后者情况中,ans值即等于N个数中的最大值,对应分法“前N-M+1个一组,后面每个数一组”)。

这样的话,ans的范围就“显然”地确定了:[N个数中的最大值, 前N-M+1个的和],我们就可以通过二分法去寻找ans的值。

这里有一个问题:我们在寻找ans值时,如何判断一个值tempans是满足题意的,换句话说,我们如何判断“在值tempans的限制下N数可以分成M组,其中每组和都不大于tempans”?我们可以用下面方法通过从头遍历N个数一次进行判断(可用反证法进行进行验证):


总时间复杂度为o(NlgM),完整代码如下:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值