代码改变世界

poj 3273 Monthly Expense ----二分

2012-03-19 21:15  java环境变量  阅读(230)  评论(0编辑  收藏  举报

Monthly Expense
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 7872   Accepted: 3241

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

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个月后一个月最多需要花多少钱。。。。题目不是很好解释。 拿题目实例说:先输入 N天和 M个月。接下来是 N天 每天需要花的钱。   输入 的是7和5.。 所以  把一二天的钱 第一个月支出,第三四天的 钱 第二个月支出。   接下来几天的钱每个月支出其中一天。。。那么着五个月中  最多的一个月只要支出 500,所以输出500。

            题目思路:  我刚开始看题,想的是贪心,最小的可能就是 元素中的最大值,从第一个开始加,没超过最小可能值 的先加起来再说,反正迟早是要加的。。但后面想一下,这样想错了。。。这题队里放在二分专题中,所以  再考虑二分,  并解决了些细节 ,AC了。

             上界max的值是所有元素之和,下界min是元素中的最大值。  每次二分。    从第一个元素开始往后加,当超过 mid, 月份+1,。  求出月份 ,如果月份比mid小,证明结构可以比mid更小,反过来如果比mid大,则证明mid不能满足,结果比mid要大。

             代码和思路:

//Memory: 556 KB		Time: 63 MS
//Language: C++		Result: Accepted
#include<stdio.h>
int a[100100];
int main()
{
	//freopen("1.txt","r",stdin);
	int n,m,i,j;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		int max=0,min=0,mid;
		for(i=0;i<n;i++)
		{
			scanf("%d",&a[i]);
			if(a[i]>min) min=a[i];
			max+=a[i];
		}
		while(min<=max)   //二分
		{
			int sum=0,t=1;
			mid=(min+max)/2;
			for(i=0;i<n;i++)
			{
				sum+=a[i]; 
				if(sum>mid)    //如果到某天超过了预算月支出。月份加1
				{
					sum=a[i];   //和初始为此天的预算支出
					t++;    
				}
			}
			if(t<=m) max=mid-1;   
			else min=mid+1;
		}
		printf("%d\n",mid);
	}
	return 0;
}