Monthly Expense 二分

版权声明:原创文章转载时请注明出处 https://blog.csdn.net/weixin_42856843/article/details/88877797

Monthly Expense 二分

Time limit:2000 ms Memory limit:65536 kB Source: USACO 2007 March Silver

描述

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.

输入

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

输出

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

Input

7 5
100
400
300
100
500
101
400

Output

500

提示

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.

代码

#include <iostream>
#include <algorithm>
#include <stdio.h>

#define PI 3.14159265358979383246
#define LL long long
#define INF 0x3f3f3f3f  

#define _for(i, a) for(int i = 0; i < (a); ++i)

using namespace std;

int pie[100000];
int N = 0, F = 0;

bool che(int x) {
	int t = 0, n = 1;
	_for(i, N) {
		t += pie[i];
		if (t > x) {
			t = pie[i];
			n++;
		}
	}
	return n <= F;
}//检验当前分法是否可行

int getpie(int left, int right) {
	int t = (right + left) / 2;
	if (right - left <= 1) return right;
	if (che(t))
		return getpie(left, t);
	else
		return getpie(t, right);
}//二分法得到最佳的分法

int main()
{
	//freopen("input.txt", "r", stdin);
	int _max = 0, sn = 0;
	cin >> N >> F;//获取花费总个数和最大分组数
	_for(i, N) {
		cin >> pie[i];
		_max = max(_max, pie[i]);
		sn += pie[i];
	}
	cout << getpie(_max - 1, sn);
	return 0;
}

本人也是新手,也是在学习中,勿喷

转载请注明出处

欢迎有问题的小伙伴一起交流哦~

猜你喜欢

转载自blog.csdn.net/weixin_42856843/article/details/88877797
今日推荐