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

输出:

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值