POJ 3273 Monthly Expense【二分】(最大值最小化)

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


题目大意就是,把n天的花费分成m组,保证每组花费和尽可能的小,然后输出分组中花费和的最大值。


代码如下:

#include <iostream>
using namespace std;
int a[100010];
int main()
{
	int n,m;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		int high=0,low=0,mid;
		for(int i=0;i<n;i++)
		{
			cin>>a[i];
			high+=a[i];
			low=max(low,a[i]);
		}
		int left=low,right=high,sum=0,cnt=0;
		
		while(left<right) // 二分 
		{
			sum=0;cnt=1;
			mid=(left+right)/2;
			for(int i=0;i<n;i++)
			{
				if((sum+a[i])<=mid){
					sum+=a[i];
				} 
				else 
				{
					sum=a[i];
					cnt++;
				}
			}
			if(cnt<=m) right=mid;
			else left=mid+1;
		}
		
		cout<<left<<endl;
	 } 
	 return 0;
 } 

博客已搬:洪学林博客

你可能感兴趣的:(C++,算法,ACM)