Monthly Expense poj3273 (二分/最大值最小化)

来源:互联网 发布:南京黑马程序员培训班 编辑:程序博客网 时间:2024/05/21 09:58

Monthly Expense
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 24044 Accepted: 9362

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 nextN (1 ≤ N ≤ 100,000) days.

FJ wants to create a budget for a sequential set of exactly M (1 ≤ MN) 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 andM
Lines 2..N+1: Line i+1 contains the number of dollars Farmer John spends on theith day

Output

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

Sample Input

7 5100400300100500101400

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组使得每组分的最少
求分组中最大的那组的数值


所以答案最大是sum  就是所有的分一个组
                最小是maxn 即n=m的时候每个自己一个组

So 利用二分在这区间寻找合适的答案

#include <iostream>#include <cstring>#include <cstdio>using namespace std;int num[100100];int main(){int n,m,i;int sum;int maxn;while(cin>>n>>m){sum = 0;maxn = 0;for(i=1;i<=n;i++){cin>>num[i];sum+=num[i];maxn=max(maxn,num[i]);}while(maxn < sum)  ///花费分组后最小就是maxn 最大 sum{int cnt=0;  ///分了几组int temp_sum=0;int mid = (maxn+sum)>>1;for(i=1;i<=n;i++){temp_sum+=num[i];if(temp_sum > mid)  ///如果 总和 大于mid 那么这个num[i]的分到下一个分组中{temp_sum=num[i];cnt++;}}if(cnt < m)  ///如果分的cnt组小于m组 那么上界小点{sum = mid;}else{maxn = mid+1;}}cout<<maxn<<endl;}return 0;}



0 0
原创粉丝点击