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
Lines 2.. N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day
Output
Sample Input
7 5 100 400 300 100 500 101 400
Sample Output
500
Hint
Source
#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;
}