POJ3273 每月的花费 二分

题目:

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.

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
/*给出农夫在n天中每天的花费,要求把n天分作m组,每组的天数必然是连续的,所有段
和的最大值最小,求那个最大值*/
/*方法:二分那个最大值x然后把n个数相当于往上界为x的袋子里装,看需要装几个袋子,是不是要比要求
的m值大*/
/*合适的解可能不止一个,要求最优解*/
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[100005];
int main()
{
    int n,m,ma,sum,low,high,cnt,mid,ans;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        sum=0;
        ma=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            if(a[i]>ma)
            {
                ma=a[i];
            }
            sum+=a[i];
        }
        low=ma;
        high=sum;
        while(low<=high)
        {
            mid=(low+high)/2;
            sum=0;
            cnt=1;
            for(int i=1;i<=n;i++)
            {
              if(sum+a[i]<=mid)
              {
                  sum+=a[i];
              }
              else
              {
                  sum=a[i];
                  cnt++;
              }
            }
            if(cnt<=m)//说明袋子容量偏大 最大值不是最优解 还可以更小
            {
                ans=mid;
                high=mid-1;
            }
            else
                low=mid+1;//说明袋子容量偏小 非解
        }
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/rain699/article/details/81784085