#二分# POJ 3273 Monthly Expense

POJ 3273

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


题目大意:


按照顺序将n个花费分为m组,要求分得各组花费之和尽可能小


解题思路:


经典二分穷举:


   遍历n个花费,最大花费为二分下界leftn个花费之和为上界right,根据每次循环所求得的mid进行如下判断:利用mid进行分组,得到的组数与m相比较,如果当前分得的组数小于m,则说明mid偏大,反之,mid偏小


代码:

#include<iostream>  
#include<map>  
#include<cstring>  
#include<cstdio>  
using namespace std;  
typedef long long LL;;  
const int MaxN = 1e5;  
  
int w[MaxN + 5];  
int n, m;  
  
bool solve(int x) {        //判断利用当前的mid能把总天数分为几组  
    int sum = 0, cnt = 1;  //cnt: 用来统计分数个数  
    for(int i = 1; i <= n; i++) {  
        if(sum + w[i] <= x) sum += w[i];  
        else {  
            sum = w[i];   //下一组  
            cnt++;  
        }  
    }  
    if(cnt > m) return 1;  //若利用mid值划分的组数比规定的要多,则说明mid值偏小  
    else return 0;         //否则mid偏大  
}  
  
int main() {  
    scanf("%d %d", &n, &m);  
    int l = 0, r = 0;  
    for(int i = 1; i <= n; i++) {  
        scanf("%d", &w[i]);  
        l = max(l, w[i]);  
        r += w[i];  
    }  
    int mid;  
    while(l <= r) {  
        mid = (l + r) / 2;  
        if( solve(mid) ) l = mid + 1;  
        else r = mid - 1;  
    }  
    printf("%d\n", mid);  
    return 0;  
}  

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值