zoukankan      html  css  js  c++  java
  • POJ 3273 二分

    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

    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天中每天的花费,要求把这n天分作m组,每组的天数必然是连续的,要求分得各组的花费之和应该尽可能地小,最后输出各组花费之和中的最大值。最大化最小值即可,二分搜索。

    下见代码:

    #include<cstdio>
    #include<iostream>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    const int maxn=100005;
    int n,m;
    int a[maxn];
    bool C(int x) //c(x)=能不能把n个数分成最多m个每个组的和不超过x的组。(有点绕,但这是重点,仔细理解)
    {
        int sum=0;
        int num=1;
        for(int i=0;i<n;i++)
        {
            sum+=a[i];
            if(sum>x)
            {
                sum=a[i];
                num++;
            }
        }
        return num<=m;
    }
    int main()
    {
        while(scanf("%d%d",&n,&m)!=EOF)
        {
             int MAX=0;
             int asum=0;
            for(int i=0;i<n;i++)
            {
                scanf("%d",&a[i]);
                MAX=max(MAX,a[i]);
                asum+=a[i];
            }
            int lb=MAX,ub=asum,ans=0;
            while(lb<=ub)
            {
                int mid=(lb+ub)/2;
                if(C(mid))
                {
                    ans=mid;
                    ub=mid-1;
                }
                else lb=mid+1;
            }
            printf("%d
    ",ans);
        }
        return 0;
    }
    


     

  • 相关阅读:
    我的第一次面试 —— 腾讯 AI安全 一面总结
    从零开始openGL——五、光线追踪
    从零开始openGL——四、纹理贴图与n次B样条曲线
    从零开始openGL——三、模型加载及鼠标交互实现
    从零开始openGL—— 二、 基本图形绘制
    NN入门,手把手教你用Numpy手撕NN(三)
    2020计算机保研经验分享
    TCP实战二(半连接队列、全连接队列)
    TCP实战一(三握四挥、流量控制)
    tcpdump抓包工具的基本使用
  • 原文地址:https://www.cnblogs.com/Zeroinger/p/5493931.html
Copyright © 2011-2022 走看看