[ACM] POJ 3273 Monthly Expense (二分解決最小化最大值)
Time Limit: 2000MS | Memory Limit: 65536K |
Total Submissions: 14158 | Accepted: 5697 |
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
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 MLines 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.Source
題意為給定一個n個數組成的序列,劃分為m個連續的區間,每個區間所有元素相加,得到m個和,m個和裡面肯定有一個最大值,我們要求這個最大值儘可能的小。
用二分查詢可以很好的解決這個問題。這類問題的框架為,找出下界left和上界right, while(left< right), 求出mid,看這個mid值是符合題意,繼續二分。最後right即為答案。
本題中的下界為n個數中的最大值,因為這時候,是要劃分為n個區間(即一個數一個區間),left是滿足題意的n個區間和的最大值,上屆為所有區間的和,因為這時候,是要劃分為1個區間(所有的數都在一個區間裡面), 1<=m<=n, 所以我們所要求的值肯定在 [left, right] 之間。對於每一個mid,遍歷一遍n個數,看能劃分為幾個區間,如果劃分的區間小於(或等於)給定的m,說明上界取大了, 那麼 另 right=mid,否則另 left=mid+1.
程式碼:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int maxn=100010;
int money[maxn];
int n,m;
int main()
{
scanf("%d%d",&n,&m);
int left=-1,right=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&money[i]);
if(left<money[i])
left=money[i];
right+=money[i];
}
while(left<right)
{
int mid=(left+right)/2;
int cnt=0;
int cost=0;
for(int i=1;i<=n;i++)
{
if(cost+money[i]>mid)
{
cnt++;//劃分區間,不包括當前的money[i]
cost=money[i];
}
else
cost+=money[i];
}
cnt++;//最後一個cost值也要佔一天
if(cnt<=m)
right=mid;
else
left=mid+1;
}
cout<<right<<endl;
return 0;
}