POJ 3273 二分求最大化最小值

Monthly Expense
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 20086 Accepted: 7916
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
题意:
有n个花费,现在要分成m段。使得每一段的和最小的那个值是所有分法里最大的。
题解:
最大化最小值或者最小化最大值的问题可以用二分法来做。为什么用二分?
以求最大化最小值问题为例。
我们知道二分有一个前提就是对有序的东西才能二分查找。也就是这个问题变量是有序的才能用二分。
在求最大化最小值时,既然求,那么这个值一定有一个范围。而求最大化最小值时。既然它可以“最大化”,那我们一般可以推到一个”最大值“。既然它可以“最小值”,那我们一般可以推到一个”最小值“。可知最终的这个“”一定在这个最大值与最小值之间的范围里。当我们在这个范围里挑一个值得时候。我们经过处理,得出一个和题目要求位置相同的变量。我们挑的这个值确定的这个变量状态与题目的要求变量进行比较。这个就是有序的。在本题中就是,但我枚举一个总和k后,求得在这个中和下的最大分段数,这个分段数与题目要求的分m段的比较是有序的。如果比m大,说明段数分多了–>说明k枚举小了,接下来再在大于k的区间枚举。这就可以二分了。

再就是唯一性问题。
一般而言最大化最小值问题都会只有一个确定的答案(如果有多个答案,也应该都是一样的值)这是显然的。那么在二分过程中我们应该是不断缩小[L,R]的范围,最终使得L==R才退出二分。这样才是一个唯一的结果。如果当我们过程中查到了某个值的状态满足题目要求就退出。我们就无法保证这是唯一的那个答案。

同类题有POJ3258 POJ1905 POJ3122

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#define f(i,a,b) for(i = a;i<=b;i++)
#define fi(i,a,b) for(i = a;i>=b;i--)

using namespace std;
#define SIZE 100000
typedef long long ll;

ll a[SIZE+10];
int n,m;

int Cnt(ll M){
    int sum = 0,cnt = 1;
    int i;
    f(i,1,n){
        sum+=a[i];
        if(sum>M){
            cnt++;
            sum = a[i];
        }
    }
    return cnt;
}

int main()
{
    while(~scanf("%d%d",&n,&m)){
        int i;
        ll sum = 0,Max = -0x3f3f3f3f;
        f(i,1,n){
            scanf("%lld",a+i);
            sum+=a[i];
            if(a[i]>Max) Max = a[i];
        }

        ll L = Max,R = sum,M;
        while(L<=R){
            M = (L+R)/2;
            int k = Cnt(M);
            if(k<=m){
                R = M-1;
            }else
                L = M+1;
        }
        printf("%lld\n",M);
    }
    return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值