POJ 3273 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 ≤ 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天每天的花费,然后把这N天划分成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 <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
int main()
{
    int N,M,money[100001];
    int low=0,high=0;
    cin>>N>>M;
    for(int i=1;i<=N;i++)
    {
        scanf("%d",&money[i]);
        if(low<money[i])
            low=money[i];
        high=high+money[i];
    }
    while(low<high)
    {
        int mid=(low+high)/2;
        int sum=0,cnt=1;//cnt表示能分成多少个消费月
        for(int i=1;i<=N;i++)
        {
            if(sum+money[i]<=mid)
            {
                sum=sum+money[i];
            }
            else
            {
                cnt++;
                sum=money[i];
            }
        }
        if(cnt<=M)//mid太大了即每个消费月的限额大了,所以消费月的个数少了
            high=mid;
        else
            low=mid+1;
    }
    cout<<high<<endl;
    return 0;
}

你可能感兴趣的:(POJ 3273 Monthly Expense (二分,最小化最大值))