看了题目没有想法,参考了其他同学的做法后,自己写了一个
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
#include <iostream>
#include <vector>
using namespace std;
int N, M;
bool judge_binary(int mid, const vector<int>& vec)
{
if (vec.size() == 0)
return false;
int group_num = 0;
int sum_up = 0;
for (vector<int>::const_iterator itr = vec.begin(); itr != vec.end(); ++itr)
{
if ((*itr + sum_up) < mid) //小于mid则累加,否则另起一组
sum_up += (*itr);
else
{
sum_up = *itr;
group_num++;
}
}
if (group_num < M) //当前分组小于预期的M组,即mid值偏大,反之mid值偏小
return false;
return true;
}
int main()
{
cin >> N >> M;
vector<int> vec;
int temp,low,high=0,mid,ic;
for (ic = 0; ic < N;++ic)
{
cin >> temp;
vec.push_back(temp);
}
low = vec[0];
for (ic = 0; ic < N;++ic)
{
if (vec[ic] > low)
low = vec[ic];
high += vec[ic];
}
mid = (high + low) / 2;
while (low<high)
{
if (!judge_binary(mid, vec))
high = mid-1;
else
low = mid+1;
mid = (high + low) / 2; //最后分得的mid为最优解
}
cout << mid << endl;
return 0;
}