#二分# 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;  
}  

猜你喜欢

转载自blog.csdn.net/jasmineaha/article/details/79121662