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.
Lines 2.. N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day
7 5 100 400 300 100 500 101 400
500
/*
题意:
给定一个n个数组成的序列,划分为m个连续的区间,每个区间所有
元素相加,得到m个和,m个和里面肯定有一个最大值,我们要求这
个最大值尽可能的小。
题解:
网上找的别人的。
本题中的下界为n个数中的最大值,因为这时候,是要划分为n个区间
(即一个数一个区间),left是满足题意的n个区间和的最大值,上届
为所有区间的和,因为这时候,是要划分为1个区间(所有的数都在一
个区间里面), 1<=m<=n, 所以我们所要求的值肯定在 [left, right]
之间。对于每一个mid,遍历一遍n个数,看能划分为几个区间,如果划分
的区间小于(或等于)给定的m,说明上界取大了, 那么 另 right=mid,
否则另 left=mid+1.
*/
#include <stdio.h>
#include <string.h>
#include<iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, k;
int num[100005];
while (cin >> n >> k)
{
int l, r;
l = 0;
r = 0;
for (int i = 0; i < n; i++)
{
cin >> num[i];
r += num[i];
l = max(l, num[i]);
}
while (l<r)
{
int mid = (l + r) / 2;
int cnt = 0;
int temp = 0;
for (int i = 0; i < n; i++)
{
if (temp + num[i] <= mid)
{
temp += num[i];
}
else
{
cnt++;
temp = num[i];
}
}
cnt++;
if (cnt <= k)
{
r = mid;
}
else
{
l = mid + 1;
}
}
cout << r << endl;
}
return 0;
}