POJ 3273 二分法穷举

本文介绍了一种算法,帮助农民约翰(FJ)优化其财务预算,通过将未来若干天的支出分配到一系列连续的月度周期中,以确定最低的月度生活费用上限。

摘要生成于 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 ≤ 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
#include <iostream>
#include <vector>
using namespace std;

int N, M;

bool judge_binary(int mid, const vector<int>& vec)
{
	if (vec.size() == 0)
		return false;
	int group_num = 0;
	int sum_up = 0;
	for (vector<int>::const_iterator itr = vec.begin(); itr != vec.end(); ++itr)
	{
		if ((*itr + sum_up) < mid)                    //小于mid则累加,否则另起一组
			sum_up += (*itr);
		else
		{
			sum_up = *itr;
			group_num++;
		}
	}
	if (group_num < M)                 //当前分组小于预期的M组,即mid值偏大,反之mid值偏小
		return false;
	return true;
}

int main()
{
	cin >> N >> M;
	vector<int> vec;
	int temp,low,high=0,mid,ic;
	for (ic = 0; ic < N;++ic)
	{
		cin >> temp;
		vec.push_back(temp);
	}
	low = vec[0];
	for (ic = 0; ic < N;++ic)
	{
		if (vec[ic] > low)
			low = vec[ic];
		high += vec[ic];
	}
	mid = (high + low) / 2;
	while (low<high)
	{
		if (!judge_binary(mid, vec))            
			high = mid-1;
		else
			low = mid+1;
		mid = (high + low) / 2;                //最后分得的mid为最优解
	}
	cout << mid << endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值