题目的大意是:给你两个数n,m。m代表给你m个数字,n代表最多分成n组。求每组连续数字最小的和。
一开始一般大家都会想到是dp但是这是不对的、、要不就不会放在计算方法的分类之中了啊、、disscuss中说是二分。后来看了一下果然是啊!就是把数列之中最大的数字和所有数字的和进行二分,求出最小的和。初始化时min = max(f[i]),max = sum(f[i]),然后再判断进行二分,如果分的组数<n,则max = mid;否则min = mid+1;一直到min > max结束。
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 11259 | Accepted: 4608 |
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 <stdio.h>
#include <string.h>
#include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;
int f[101000];
int main()
{
int n, m, i;
int mid, _max, _min;
cin >>m>>n;
_min = 0;
_max = 0;
for(i = 0; i < m; i++)
{
cin >>f[i];
_max += f[i];
if(f[i] > _min)
_min = f[i];
}
while(_min < _max)
{
mid = (_min+_max)/2;
int sum = 0, cnt = 0;
for(i = 0; i < m; i++)
{
sum += f[i];
if(sum > mid)
{
cnt ++;
sum = f[i];
}
}
if(cnt < n)
_max = mid;
else
_min = mid+1;
}
cout <<_min<<endl;
return 0;
}