POJ 3273 Monthly Expense -二分区间最小的最大值

题目:

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.


输入:

Line 1: Two space-separated integers: <i>N</i> and <i>M</i><br>Lines 2..<i>N</i>+1: Line <i>i</i>+1 contains the number of dollars Farmer John spends on the <i>i</i>th day

扫描二维码关注公众号,回复: 2191833 查看本文章

输出:

Line 1: The smallest possible monthly limit Farmer John can afford to live with.

样例:

7 5
100
400
300
100
500
101
400

500

题目大意:给定n个数组成的序列,要划分为m个连续的区间,并且有m个区间的和,使得m个和中最大值尽可能小。

思路:给出上界和下界,求出mid,看用这个mid划分的区间是不是符合题意。

1.如果划分的区间是小于m,mid太大了,改变上界,right=mid;
2.如果划分的区间是大于m,mid太小了,改变下界,left=mid+1;

代码:

#include<iostream>
#define maxn 10010
using namespace std;
int money[maxn];
int n,m;

int main()
{
    cin>>n>>m;
    int left=0,right=0;
    for(int i=1;i<=n;i++)
    {
        cin>>money[i];
        left=max(money[i],left);
        right+=money[i];
    }
    while(left<right)
    {
        int mid,cnt=0,cost=0;
        mid=(left+right)/2;
        for(int i=1;i<=n;i++)
        {
            if(cost+money[i]>mid)
            {
                cnt++;//划分区间,这个比较含当前的money,但划分区间内不含当前的money
                cost=money[i];
            }
            else
                cost+=money[i];
        }
        cnt++;
        if(cnt<=m)
            right=mid;
        else
            left=mid+1;
    }
    cout<<right<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wentong_xu/article/details/80780202