POJ3273--Monthly Expense

本文介绍了一种用于划分预算的算法,该算法旨在帮助农民John通过将连续的支出天数划分为多个周期(称为“fajomonths”),来确定其每月的支出限制,从而最小化最高支出周期的成本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 ≤ MN) 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
/*
对于每个mid值,看能包成几包,如果包数比m小,显然我们取大了。
因为每个包包的天数都是连续的,所以我们可以针对起点,来二分
枚举终点。这样的话就需要一个数组来存前缀和
*/
#include <iostream>
#include <cstdio>
using namespace std;
int cost[100008];
int S[100008];
int day,bag;
inline int max(int a,int b)
{
	return a>b?a:b;
}
int f(int x)
{
	int bb=0,l=1,r=day,wei=0,tou=0;
	while(wei!=day)
	{
		bb++;
		l=tou,r=day;
		while(l<r)
		{
			int mid=(l+r)/2;
			if(S[mid]-S[tou]>x)//无法包在体积为x的包里
			{
				r=mid;
			}
			else l=mid;
			if(l+1==r)
			{
				if(S[r]-S[tou]<=x)
				{
					l=r;
				}
				break;
			}
		}
		tou=l;
		wei=l;
	}
	return bb;
}
int main()
{
	while(scanf("%d%d",&day,&bag)==2)
	{
		int minv=0;
		for(int i=1;i<=day;i++)
		{
			S[0]=0;
			scanf("%d",&cost[i]);
			if(i==1)S[i]=cost[i];
			else S[i]=S[i-1]+cost[i];
			minv=max(minv,cost[i]);
		}
		int l=minv,r=S[day];//上限就是把全部的钱都包在一个包里。下限如果不弄最大消费那天的话,在最上面那个二分得特殊处理否则死循环
		while(l<r)
		{
			int mid=(l+r)/2;
			if(f(mid)<=bag)
			{
				r=mid;
			}
			else l=mid;
			if(l+1==r)
			{
				if(f(l)>bag)
				{	
					l=r;
				}
				break;
			}
		}
		printf("%d\n",l);
	}
	return 0;
}

		

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值