POJ3273 Monthly Expense【二分】

Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 32920   Accepted: 12370

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.

Source


问题链接POJ3273 Monthly Expense

问题简述

  给N个数(顺序不变),划分为M块。对各个块求和,使得和的最大值为最小。找出这个最大和的最小值。

问题分析

  首先,对所有数求总和,求最大值。那么,最大和的最小值介于最大值和总和之间。如果一个数划分为一块,则答案为最大值;如果所有数划分为一块(只有一块),则答案为总和。

  在此基础上进行二分查找,找到最大和的最小值即可,其前提是划分为M块。对于暂时的结果,如果其块数大于给定的M,则通过增大暂时结果继续重新划分搜索;如果其块数量小于给定的M,则减少暂时的结果继续重新划分搜索。

程序说明:(略)

题记:(略)

参考链接:(略)


AC的C++语言程序如下:
/* POJ3273 Monthly Expense */

#include <iostream>
#include <stdio.h>

using namespace std;

const int N = 1e5;
int a[N + 1];

int main()
{
    int n, m;

    while(~scanf("%d%d", &n, &m)) {
        int sum = 0, maxa = 0;
        for(int i = 0; i < n; i++) {
            scanf("%d", &a[i]);
            sum += a[i];
            maxa = max(maxa, a[i]);
        }

        int low = maxa, high = sum, mid;
        while(low <= high) {
            mid = (low + high) / 2;

            int cnt = 1;
            sum = 0;
            for(int i = 0; i < n; i++) {
                sum += a[i];
                if(sum > mid) {
                    sum = a[i];
                    cnt++;
                }
            }

            if(cnt <= m) {
                maxa = mid;
                high = mid - 1;
            } else
                low = mid + 1;
        }

        printf("%d\n", maxa);
    }

    return 0;
}







猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/80490892