POJ3273 Monthly Expense(二分法)

10 篇文章 0 订阅

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

分析:
这题我想了好长时间就是不会啊,虽然知道是最小化最大值,但是就是不知道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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值