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;
}
发布了204 篇原创文章 · 获赞 16 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43846139/article/details/103662917