Monthly Expense(二分法)

来源:互联网 发布:航运货代 知乎 编辑:程序博客网 时间:2024/06/06 18:44

Monthly Expense

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 64   Accepted Submission(s) : 19
Problem 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: <i>N</i> and <i>M</i><br>Lines 2..<i>N</i>+1: Line <i>i</i>+1 contains the number of dollars Farmer John spends on the <i>i</i>th day
 

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

Sample Input
7 5100400300100500101400
 

Sample Output
500
 

Source
PKU
 

题意:题意为给定一个n个数组成的序列,划分为m个连续的区间,每个区间所有元素相加,得到m个和,m个和里面肯定有一个最大值,我们要求这个最大值尽可能的小。

思路:用二分查找可以很好的解决这个问题。这类问题的框架为,找出下界left和上界right, while(left< right), 求出mid,看这个mid值是符合题意,继续二分。最后right即为答案。

代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <string>#include <map>#include <stack>#include <vector>#include <set>#include <queue>#include <iomanip>#define maxn 15#define mod 1000000007#define inf 0x3f3f3f3f#define exp 1e-6#define pi acos(-1.0)using namespace std;int a[100010];int main(){    //ios::sync_with_stdio(false);    int n,m;    int i;    int minn=-inf;    int sum=0;    cin>>n>>m;    for(i=0;i<n;i++){ cin>>a[i]; if(minn<a[i]) minn=a[i];sum+=a[i]; }    int left=minn,right=sum,mid;    while(right-left>exp)    {        int cnt=0;        int sum1=0;        mid=(left+right)/2;        for(i=0;i<n;i++)        {            if(sum1+a[i]>mid){cnt++;sum1=a[i];}            else            {                sum1+=a[i];            }        }        cnt++;   //注意此处最后一个花费的仍需要加一        if(cnt<=m) right=mid;        else left=mid+1;    }    cout<<right<<endl;}



原创粉丝点击