Monthly Expense (POJ-3273)(二分查找)

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.

题意:有一个农夫很精明,然后他知道每个月花费的钱,但是他想把他的钱分成好多周期去花,然后把花费最大的周期最小化,然后让你求出农夫的最小的月收入限制。

思路:想到这道题是让你创建许多周期,然后找最小,就可以看出这是很明显的二分,我们把最小的和总和进行二分,然后每次查找最小值即可,还要注意范围和查找的限制。

AC代码:

#include <stdio.h>
#include <string>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
typedef long long ll;
const int maxx=100010;
const int inf=0x3f3f3f3f;
using namespace std;
int n,m;
int a[maxx];
bool erfen(int mid)
{
    int start=0,len=1;
    for(int i=1; i<=n; i++)
    {
        if(a[i]+start<=mid)
            start+=a[i];
        else
        {
            start=a[i];
            len++;
        }

    }
    if(len>m)
        return false;
    else
        return true;
}
int main()
{
    cin>>n>>m;
        double high=0,last=0;
        for(int i=1; i<=n; i++)
        {
            cin>>a[i];
            high+=a[i];
            if(last<a[i])
                last=a[i];
        }
        int mid=(last+high)/2;
        while(last<high)
        {
            if(!erfen(mid))
            {
                last=mid+1;
            }
            else
                high=mid-1;
            mid=(last+high)/2;
        }
        cout<<mid<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值