POJ 3273 Monthly Expense

来源:互联网 发布:添加网络监视器 编辑:程序博客网 时间:2024/06/06 03:34

Description

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 nextN (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 andM
Lines 2..N+1: Line i+1 contains the number of dollars Farmer John spends on theith day

Output

Line 1: The smallest possible monthly limit Farmer John can afford to live with.

Sample Input

7 5100400300100500101400

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 lim






二分,关键是一个数组的遍历,学习了
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<limits.h>
using namespace std;
int y[100000+10];
int main(void)
{
    int i,j,n,m,num,minn;
    long long maxn=0;
    scanf("%d%d",&n,&m);
    minn=INT_MIN;
    for(i=0;i<n;i++)
    {
        scanf("%d",&y[i]);
        maxn+=y[i];
        if(y[i]>minn)
            minn=y[i];
    }
    long long l,r,zhongjian,sum;
    l=minn-1;
    r=maxn;

    while(r-l>1)
    {
        zhongjian=(l+r)/2;
        num=0;
        j=0;
        sum=0;
        for(int k=0;k<n;k++)
        {
            sum+=y[k];
            if(sum>zhongjian)
            {
                num++;
                sum=y[k];
            }
        }
        if(sum!=0)
            num++;
        if(num<=m)
        {
            r=zhongjian;
            //printf("Now l=%d and r=%d\n",l,r);
        }
        else
            {
                l=zhongjian;
                //printf("Now l=%d and r=%d\n",l,r);
            }
    }
    printf("%d",r);
    return 0;
}
0 0
原创粉丝点击