POJ3273 Monthly Expense(二分法)

来源:互联网 发布:淘宝网镂空针织衫 编辑:程序博客网 时间:2024/06/14 23:11

问题描述:
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 5100400300100500101400

Sample Output

500

分析:
这题我想了好长时间就是不会啊,虽然知道是最小化最大值,但是就是不知道C(d)这个函数如何写。

我当时定义C(d)为是否可以安排分成M组后,每组和都不大于d
所以在函数里需要我们自己来分成M组,即N个数分成M组,这咋分,我懵逼了。无奈想了半天,查了题解QAQ,我也不想啊!!

实际应该定义C(d)为是否需要M以上个分期才使得每个分期的花费不大于d,也就是说我们来统计不大于d的分组情况,而不是我们来分组来判断是否不大于d,有时候将思维逆一下可能会变得简单很多,很多很容易想到的方法一般都不容易实现,所以逆向思维很重要。

细节:lb初始化为序列中最大的数,因为相当于每个数自己为一组。其实ub应该初始化为序列的和,因为相当于整个序列只分一组。但是直接用INF代替也是没问题的。

代码如下:

#include<cstdio>using namespace std;const int maxn = 100000+10;const int INF = 1000000000;int N,M;int n[maxn];/*C(d)是否需要M以上个分期才使得每个分期的花费不大于d*/bool C(int d){    int sum = 0;    int group = 1;    for(int i=0; i<N; i++)    {        sum+=n[i];        if(sum > d)        {            sum = n[i];            group++;        }    }    if(group > M) return true;    else return false;}void solve(){    int max = n[0];    for(int i=1; i<N; i++)    {        if(max < n[i]) max = n[i];    }    int lb = max, ub = INF;    while(ub - lb > 0)    {        int mid = (lb+ub) / 2;        if(C(mid)) lb = mid + 1;        else ub = mid;    }    printf("%d\n",lb);    return;}int main(){    scanf("%d%d",&N,&M);    for(int i=0; i<N; i++)    {        scanf("%d",&n[i]);    }       solve();    return 0;}
0 0
原创粉丝点击