POJ 3273 Monthly Expense(二分法解决最大中找最小问题)

博客围绕将n个数组成的序列划分为m段,使最大段和最小的问题展开。介绍可用二分查找解决,思路是找出上下界,通过循环求中间值并动态改变上下界,直至找到答案,还给出了相关代码示例。

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.

题目的意思是让把n个数组成的序列划分为m段,每种划分方式都会有一段数字之和是这m段中最大的那一段,我们的任务就是确定一种划分方式使最大的那一段最小。
这种问题可以用二分查找解决,思路是找出上界right和下界left,while(left<right)求mid=(left+right)/2,再根据结果动态改变left或right的值,在本题中如果mid<=m说明上界太大了,就要让right=mid,如果mid>m说明下界太小了,要让left=mid+1,到最后当left==right的时候说明找到答案了。
下面是代码:

#include<iostream>
using namespace std;
int dat[100005];
int main()
{
	int n,m;
	int left=-1,right=0,mid,ci,sum;
	cin>>n>>m;
	for(int i=1;i<=n;++i)
	{
		cin>>dat[i];
		if(left<dat[i]) left=dat[i];
		right+=dat[i];
	}
	while(left<=right)
	{
		mid=(left+right)/2;
		ci=0;
		sum=0;
		for(int i=1;i<=n;++i)
		{
			if(sum+dat[i]>mid)
			{
				sum=dat[i];
				ci++;
			}
			else sum+=dat[i];
		}
		ci++;//千万别忘了加上最后一组!!!
		if(ci<=m) right=mid-1;
		else left=mid+1;
	}
	cout<<left<<endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值