OJ 21658::Monthly Expense (binary search + minimize maximum)

 
 

Description

Farmer John is an astounding accounting genius who has understood that he may run out of money that is supposed to keep the farm running every month. He has calculated his moneyi(1<=moneyi<=10,000) for each of the next N(1<=N<=100,000) working days, and he wants to pay for his consecutive M(1<=M<= Make a budget for N) closing periods called "clearing months", each "clearing month" consists of one working day or more consecutive working days, and each working day is included in only one "clearing month" . FJ's goal is to schedule these "liquidation months" so that the largest of each liquidation month's spending is minimized, thereby determining his monthly spending limit.

Input

First line: two integers separated by spaces: N and M

Lines 2..N+1: Line i+1 contains what FJ spent on his ith working day

Output

The first line: the amount of money that can keep the farm running smoothly each month

answer:

M<=N, if it is divided into <M clearing months to meet the requirements, it can also be divided into M clearing months.

The maximum value is the smallest, and dichotomy is considered.

One ans in two.

Then simulate trying to use up the money every day,

Get a required liquidation month number cnt.

If cnt<=M is ​​legal, otherwise illegal.

Idea: We can until this value must be between the maximum value of all numbers and the sum of all numbers, then just divide this interval into two

AC code:

#include<stdio.h>
#include<algorithm>
using namespace std;
int n,m;
int a[100100];
bool mmp(int mid)
{
    int sum=0;
    int ans=1;
    for(int i=1;i<=n;i++)
    {
        if(sum+a[i]<=mid)
            sum+=a[i];
        else
        {
            sum=a[i];
            years ++ ;
        }
    }
    if(ans > m)
        return 0;

        return 1;
}
intmain ()
{

    int tail,head,mid;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        tail=0,head=1;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            tail+=a[i];
            head=max(head,a[i]);
        }

        mid=(head+tail)/2;
        while(tail>=head)
        {
            if(mmp(mid)==0)
                head=mid+1;
            else
                tail=mid-1;

                mid=(head+tail)/2;
        }
        printf("%d\n",mid+1);
    }
}
View Code

After the question: learn what is minimizing the maximum value and maximizing the minimum value

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324727327&siteId=291194637