CSU-ACM2017暑假集训2-二分搜索 poj-32732 Monthly Expense

来源:互联网 发布:手机看pdf软件 编辑:程序博客网 时间:2024/06/05 02:39

题目:

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 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 limit.

            题意:有一连串的日子,农场主对每天要花的支出都有记录,现在他想把这些单独的N天压缩为M个月,每个月包含连续的天数(数量任意)

,并给这些月份分配一个总支出限额(也就是这个月里的每天的支出之和不能超过的数),要求这个限额最小是多少。

            思路:二分答案,注意对边界的计算。

代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int n,m;int money[111111];int maxm;int judge(int x){    int counts,l,r;    counts=l=0;    r=1;    while(1)    {        int sum=money[l];        if(sum>x)            return 0;        while(r<n)        {            if(sum+money[r]<=x)                sum+=money[r++];            else                break;        }        l=r++;        counts++;        if(l==n)        {            if(counts<=m)                return 1;            else                return 0;        }    }}int bs(int l,int r){    int mid;    while(l<=r)    {        mid=(r-l)/2+l;        if(judge(mid))            r=mid-1;        else            l=mid+1;    }    return r+1;}int main(){    while(scanf("%d%d",&n,&m)!=EOF)    {        maxm=-1;        for(int i=0;i<n;i++)        {            scanf("%d",&money[i]);            maxm=max(maxm,money[i]);        }        int ans=bs(0,maxm*m);        printf("%d\n",ans);    }    return 0;}


阅读全文
0 0
原创粉丝点击