D - Monthly Expense

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

题意:

一个农夫为了避免农场倒闭,开始计划支出。现在有N天,每天都必须支出Mi元,现在要求把这N天分成M个月(每个月中必须是连续的天数),让我们来安排月份,使得每个月支出的钱最少。

解题思路:

对结果进行二分,假设每月支出的钱为X,一天一天的减去支出,如果不足以减去下一天的支出,就说明得另起一个月,把月数记录下来,如果总月数小于M,则说明X可行,否则说明X不足以支出。如果找到和合适的X就继续找更大的,否则就找小的。

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
int a[100010];
int main()
{
    int N,M;
    //freopen("1.txt","r",stdin);
    while(cin>>N>>M){
        int maxs=0;int sum=0;
        for(int i=0;i<N;i++){
            cin>>a[i];sum+=a[i];
            maxs=max(maxs,a[i]);
        }
        int high=sum,low=maxs,mid;//所求值定在high和low之间;
        while(low<high){
            int s=0,cou=0;mid=(low+high)>>1;
            for(int i=0;i<N;i++){
                s+=a[i];
                if(s>mid){
                    cou++;s=a[i];
                }
            }
            if(cou<M)high=mid;
            else low=mid;
        }
        cout<<low<<endl;
    }

}
这个题的思路现在都觉得在开飞机,完全没想到。其中利用M来分组也是特强,之前一直没想到如何去把N分成M组,而这里先确定值的范围,也就是high,low,然后得到mid,由mid去分组,然后看能否得到相应的分组数,并不断将此mid向最终的答案推进;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值