Monthly Expense(二分法)

本文介绍了一个经典的预算划分问题,目标是在给定的连续日期花费数组中,将其划分为若干个连续区间,使得这些区间内的总花费最大值最小。通过使用二分查找的方法来高效地解决这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Monthly Expense

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 64   Accepted Submission(s) : 19
Problem 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 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: <i>N</i> and <i>M</i><br>Lines 2..<i>N</i>+1: Line <i>i</i>+1 contains the number of dollars Farmer John spends on the <i>i</i>th 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
 

Source
PKU
 

题意:题意为给定一个n个数组成的序列,划分为m个连续的区间,每个区间所有元素相加,得到m个和,m个和里面肯定有一个最大值,我们要求这个最大值尽可能的小。

思路:用二分查找可以很好的解决这个问题。这类问题的框架为,找出下界left和上界right, while(left< right), 求出mid,看这个mid值是符合题意,继续二分。最后right即为答案。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#include <iomanip>
#define maxn 15
#define mod 1000000007
#define inf 0x3f3f3f3f
#define exp 1e-6
#define pi acos(-1.0)
using namespace std;
int a[100010];
int main()
{
    //ios::sync_with_stdio(false);
    int n,m;
    int i;
    int minn=-inf;
    int sum=0;
    cin>>n>>m;
    for(i=0;i<n;i++){ cin>>a[i]; if(minn<a[i]) minn=a[i];sum+=a[i]; }
    int left=minn,right=sum,mid;
    while(right-left>exp)
    {
        int cnt=0;
        int sum1=0;
        mid=(left+right)/2;
        for(i=0;i<n;i++)
        {
            if(sum1+a[i]>mid){cnt++;sum1=a[i];}
            else
            {
                sum1+=a[i];
            }
        }
        cnt++;   //注意此处最后一个花费的仍需要加一
        if(cnt<=m) right=mid;
        else left=mid+1;
    }
    cout<<right<<endl;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值