POJ 3273.Monthly Expense

538

题目



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



题解


神奇的二分法,最后答案必然在最大值和总和之间
因此下界为最大值,上界为总和

判断函数判断连续多个(或一个)数是否大于要判断的数
如果大于就将最新的数分到新的一组
根据是否能分成 m 组来判断应该查找左侧还是右侧

二分的时间复杂度是 O(logn)
判断的时间复杂度是 O(n)
总的时间复杂度是 O(nlogn)

代码


/*
By:OhYee
Github:OhYee
Blog:http://www.oyohyee.com/
Email:oyohyee@oyohyee.com

かしこいかわいい?
エリーチカ!
要写出来Хорошо的代码哦~
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <bitset>
using namespace std;

const int INF = 0x7FFFFFFF;
const int maxn = 100005;

int a[maxn];

long long sum;
int n,m;

bool Could(long long num) {
    int per = 0,g = 1;
    for(int i = 1;i <= n;i++) {
        if(per + a[i] > num) {
            g++;
            per = a[i];
            if(g > m)
                return false;
        } else {
            per += a[i];
        }
    }
    return true;
}

long long Division(long long l,long long r) {
    if(l == r) {
        return l;
    }
    long long mid = (l + r) / 2;
    if(Could(mid))
        return Division(l,mid);
    else
        return Division(mid + 1,r);
}

bool Do() {
    if(!(cin >> n >> m))
        return false;
    sum = 0;
    int Max = 0;
    for(int i = 1;i <= n;i++) {
        cin >> a[i];
        sum += a[i];
        Max = max(Max,a[i]);
    }

    cout << Division(Max,sum) << endl;

    return true;
}

int main() {
    while(Do());
    return 0;
}
发布评论
  • 点击查看/关闭被识别为广告的评论