Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 10521 | Accepted: 4298 |
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
大致题意:
给出农夫在n天中每天的花费,要求把这n天分作m组,每组的天数必然是连续的,要求分得各组的花费之和应该尽可能地小,最后输出各组花费之和中的最大值
下面是AC代码和详解:
#include<iostream>
const int MAX=100001;
int money[MAX];
int n;//天数
int m;//规定的分组数
using namespace std;/*判断用当前的mid值能把天数n分成几组*/
int main()
{
int i,j;
int mid,minn,maxn;
bool panduan(int value,int *money);
while(cin>>n>>m)
{
maxn=0;//下界
minn=0;//上界
for(i=0;i<n;i++)
{
cin>>money[i];
if(money[i]>minn)//把n天中花费最多的那一天的花费作为下界minn(相当于把n天分为n组)
minn=money[i];
maxn+=money[i];//把所有天数的总花费作为上界maxn(相当于把n天都分作1组)
}
while(minn<maxn)//那么要求的值必然在[minn,maxn]范围内
{
mid=(minn+maxn)/2;
if(panduan(mid,money))//可能在minn==maxn之前,分组数就已经=m,但是mid并不是最优,因此要继续二分
minn=mid+1;//mid值偏小,下界前移
else
maxn=mid-1;//mid值偏大,上界后移
}
mid=(minn+maxn)/2;//符合条件时,要进行最后一次二分,这时二分搜索最后得到的mid值必然是使得分组符合要求的最优值
cout<<mid<<endl;
}
return 0;
}
bool panduan(int value,int *money)
{
int i,zushu;
int sum;
zushu=1;//当前mid值能把n天分成的组数(初始把全部天数作为1组)
sum=0;
for(i=0;i<n;i++)//从第一天开始向下遍历每天的花费
{
if(sum+money[i]<=value)//当前i天之和<=mid时,把他们归并到一组
{
sum+=money[i];
}
else//若 前i-1天之和 加上第i天的花费 大于mid
{
sum=money[i];//则把前i-1天作为一组,第i天作为下一组的第一天
zushu+=1;//此时划分的组数+1
}
}
if(zushu>m)/*通过比较zushu与m的大小,对mid值进行优化*/
return true;//若利用mid值划分的组数比规定的组数要多,则说明mid值偏小
else
return false;//否则mid值偏大
}