Half of exercises 8 monthly cost solution to a problem

Title Description

Farmer John is a shrewd accountant. He realized that he might not have enough money to maintain the operation of the farm. He calculated and recorded the cost of the next N (1 ≤ N ≤ 100,000) days needed every day.
John intends to create a budget for the continuous M (1 ≤ M ≤ N) financial period, he put a financial period named fajo months. Each month contains fajo a day or consecutive days, every day is exactly included in a fajo months.
John's goal is to rationalize the number of days per month fajo included, making the most cost fajo monthly cost as little as possible.

Input Format

The first line contains two integers N, M, separated by a single space.
Next N rows, each row contains an integer between 1 to 10,000, in the order given in the next N days the daily cost.

Output Format

An integer that is the minimum value of the maximum monthly cost.

Sample input

7 5
100
400
300
100
500
101
400

Sample Output

500

prompt

If John the month as two days ago, the third and fourth two days a month, the last three days as a day a month, the maximum monthly cost is 500. Any other allocation scheme will be greater than this value.

Topic analysis

This question relates to the algorithm: Two points. Is the use of "half the answer" to solve the problem.
This question is in fact "the maximum to minimize" That's exactly the same questions. Just not the same as the title describes.
First, we need to write a function \ (bool check (int num) \) to determine the number of days per month fajo is set to \ (num \) days meets the requirements.
Then we set \ (L = 0 \) (left boundary), provided \ (R & lt ^ = 10. 9 \) (right border), divided by two, and can ultimately "minimizing a maximum" out the problem solving satisfied as the minimum cost of a month of fajo conditions.
Implementation code with the "maximum minimized."
Codes are as follows:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n, m, a[maxn], sum;
// check函数用于验证每个fajo月的开销设为num是否可行
bool check(int num) {
    int id = 1, tot = 0;
    for (int i = 0; i < n; i ++) {
        if (num - tot >= a[i]) tot += a[i];
        else if (a[i] > num) return false;
        else {
            id ++;
            tot = a[i];
            if (id > m) return false;
        }
    }
    return true;
}
int main() {
    cin >> n >> m;
    for (int i = 0; i < n; i ++) {
        cin >> a[i];
        sum += a[i];
    }
    int L = 0, R = sum, res;
    while (L <= R) {
        int mid = (L + R) / 2;
        if (check(mid)) {
            res = mid;
            R = mid - 1;
        }
        else L = mid + 1;
    }
    cout << res << endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/zifeiynoip/p/11450635.html