# G - Monthly Expense解题报告（黄杰）

3431人阅读 评论(0)

G - Monthly Expense
Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

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

Line 1: Two space-separated integers: N and M
Lines 2..N+1: Line i+1 contains the number of dollars Farmer John spends on the ith day

Output

Line 1: The smallest possible monthly limit Farmer John can afford to live with.

Sample Input

7 5
100
400
300
100
500
101
400

Sample Output

500

Hint

If Farmer John schedules the months so that the first two days are a month, the third and fourth are a month, and the last three are their own months, he spends at most \$500 in any month. Any other method of scheduling gives a larger minimum monthly limit.

m,显然是不满足的，如果小于，那么划分m组是绰绰有余的，等于就不用说了。。重要的是注意确定一个分段点后，起点在哪儿，是最后一个满足的数？还是接下来这个不满足的数？而且要注意比较一天的情况，因为一天也可能是一个周期。代码有详细的标注。

#include<stdio.h>
#define MAX 100003
int main()
{
int N,M;
int low,high,mid;
int i,res,mon,sum,days,a[MAX];//res记录合适的周期金钱，mon记录分了多少个周期，sum记录连续几天的金钱和，days记录连续几天是可行的，mon记录间断点。
while(scanf("%d%d",&N,&M)!=EOF)
{
high=0;
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
high+=a[i];
}
low=0;
while(high-low>=0)
{
sum=0;
mon=0;
days=0;
mid=(high+low)/2;
for(i=0;i<N;i++)
{
if(a[i]+sum>mid)
{
sum=0;
if(days>=1)//days是用来分别几天和0天的情况，即是否存在至少一天满足要求。
{
i--;//当出现间断点时，即此时间断点在i和i-1之间，a[i]是不符合要求的，所以下一轮要作为起点，所以i--.
days=0;//且days要清0.
mon++;//间断点加一。
}
else
{
mon=-1;//如果只一天得金钱都不符合，则赋值-1，并跳出。
break;
}
}
else//如果仍满足，sum则累加，连续的天数加一。
{
sum+=a[i];
days++;
}
if(mon==-1)//如果有一天的金钱比mid大，则退出，不需在循环。
break;
}
if(mon==-1)
{
low=mid+1;
continue;
}
if(mon+1>M)//因为mon是间断点，所以是将整个天数分为mon+1块。
low=mid+1;
else
{
high=mid-1;
res=mid;//符合则记录。
}
}
printf("%d\n",res);
}
return 0;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：206102次
• 积分：3538
• 等级：
• 排名：第9297名
• 原创：127篇
• 转载：49篇
• 译文：0篇
• 评论：14条
阅读排行
评论排行
最新评论