poj3273

来源:互联网 发布:电脑截图软件 编辑:程序博客网 时间:2024/05/17 02:00
Monthly Expense

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 5100400300100500101400

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

USACO 2007 March Silver
二分法。注意等号要放在上界优化。
代码如下:
#include<iostream>using namespace std;int expense[100000];int main(void) {    int n, m;//天数,规定的分组数    while (cin >> n >> m) {        int sum = 0;        int max = 0;        for (int i = 0; i < n; i++) {            cin >> expense[i];            sum += expense[i];            if (expense[i] > max)                max = expense[i];        }        int up = sum;        int low = max;        int mid = (up + low) / 2;        while (low < up) {//判断用当前的mid值能把天数n分成几组,通过比较group与m的大小,对mid值进行优化            int tmp = 1;//当前mid值能把n天分成的组数(初始把全部天数作为1组)              sum = 0;            for (int i = 0; i < n; i++) {//从第一天开始向下遍历每天的花费                if (sum + expense[i] < mid)//当前i天之和<=mid时,把他们归并到一组                      sum += expense[i];                else {//若 前i-1天之和 加上第i天的花费 大于mid                      sum = expense[i];//则把前i-1天作为一组,第i天作为下一组的第一天                     tmp++;//此时划分的组数+1                 }            }            if (tmp <= m)                up = mid - 1;//若利用mid值划分的组数比规定的组数要少,则说明mid值偏大,上界下移            else                low = mid + 1;//若利用mid值划分的组数比规定的组数要多,则说明mid值偏小,下界上移            mid = (up + low) / 2;        }        cout << mid << endl;    }    return 0;}



原创粉丝点击