POJ-3273-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
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
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
题意:
将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),完整代码如下: