Monthly Expense POJ - 3273(二分)

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.
輸入
第1行:兩個以空格分隔的整數: N和 M
行2 … N +1:行 i +1包含農夫約翰第i天 花費的數量
輸出
第1行:Farmer John可以承受的最低月限額。
樣本輸入
7 5
100
400
300
100
500
101
400
樣本輸出
500
提示
如果Farmer John安排這幾個月,前兩天是一個月,第三個和第四個是一個月,最後三個是他們自己的月份,他在任何一個月花費最多500美元。任何其他調度方法都會給出較大的最小月限

題意:

m個月內,每個月可以包含任意多個花費,共有n個花費,找一個最小的每月最大花費,

思路:

1.我們二分最大花費,然後遍歷n個花費;
2.用cnt記錄該mid需要多少月,k記錄花費,當k加上該花費後當月的花費要大於當前的mid時 (因爲遍歷的是最大花費),該花費不能加到當前月,而是加到下一月中,此時記錄的月份cnt++;
3.遍歷完之後,如果當前的mid需要的月份cnt>m個月,說明該mid偏大,反之偏小;
4.二分的上下界:下界可以是所有花費中的最大值(因爲每個月至少包含一次花費),上界可以是n個花費加起來(因爲最大的情況就是一個月包含了所有花費);

#include<stdio.h>
#include<algorithm>
#include<string.h>
#define ll long long
#define PI  3.14159265358979323846
#pragma GCC optimize(2)
using namespace std;
const ll maxn=1e5+7;
const int INF=1e9+7;
const double esp=1e-6;
ll price[maxn];
int main()
{
    ll n,m;
    scanf("%lld%lld",&n,&m);
    ll l=-INF,sum=0;
    for(int i=1;i<=n;i++)
    {
        scanf("%lld",&price[i]);
        sum+=price[i];
        l=max(l,price[i]);
    }
    ll r=sum;
    ll mid;
    while(r-l>=0)
    {
        mid=(l+r)>>1;
        ll cnt=1;
        ll k=0;
        for(int i=1;i<=n;i++)
        {
           if(k+price[i]<=mid)
                k+=price[i];
           else
           {
               cnt++;
               k=price[i];					//這裏wa了幾次,因爲沒有把超過的花費加到下一個月中;
           }
        }
        if(cnt>m)
        l=mid+1;
        else
        r=mid-1;
    }
    printf("%lld\n",l);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章