Drying(二分)

It is very hard to wash and especially to dry clothes in winter. But Jane is a very smart girl. She is not afraid of this boring process. Jane has decided to use a radiator to make drying faster. But the radiator is small, so it can hold only one thing at a time.

Jane wants to perform drying in the minimal possible time. She asked you to write a program that will calculate the minimal time for a given set of clothes.

There are n clothes Jane has just washed. Each of them took ai water during washing. Every minute the amount of water contained in each thing decreases by one (of course, only if the thing is not completely dry yet). When amount of water contained becomes zero the cloth becomes dry and is ready to be packed.

Every minute Jane can select one thing to dry on the radiator. The radiator is very hot, so the amount of water in this thing decreases by k this minute (but not less than zero — if the thing contains less than k water, the resulting amount of water will be zero).

The task is to minimize the total time of drying by means of using the radiator effectively. The drying process ends when all the clothes are dry.

Input
The first line contains a single integer n (1 ≤ n ≤ 100 000). The second line contains ai separated by spaces (1 ≤ ai ≤ 109). The third line contains k (1 ≤ k ≤ 109).

樣本輸入#1
3
2 3 9
5
樣本輸入#2
3
2 3 6
5
樣本輸出#1
3

樣本輸出#2
2

題意:

題意有點難理解,有n個洗完的衣服,每個含有a[i]的水,自然晾乾每分鐘涼1水量,只有一個乾燥器,一次只能乾燥一件衣服,每分鐘可乾燥k水量,問最小化的乾燥時間(所有衣服);

解題思路:

二分所需要乾燥的時間mid,如果我們用這麼多時間晾乾衣服,那麼衣服中水的含水量低等於mid的可以自動晾乾,只需要處理大於mid的衣服,對這些衣服,如果花時間t用來乾燥,那麼就有**(mid-t)的時間自動晾乾**,所以對當前的a[i]>=t*k+(mid-t),所以儘可能小的時間就是t=(a[i]-mid)/(k-1)遍歷每個a[i],記錄時間t,如果t大於當前mid,說明該mid時間不夠,反之mid偏大;
剛開始懷疑這個思路,因爲有可能某個衣服只需要乾燥一下,然後不管,後來想二分可以遍歷每個時間,把所有情況都包括
ac:

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
#define ll long long
#define PI  3.14159265358979323846
#pragma GCC optimize(2)
using namespace std;
const ll maxn=1e5+7;
const ll INF=1e10+7;
ll a[maxn];
ll n,k;
bool judge(ll m)
{
    ll temp,num=0;
    for(int i=1;i<=n;i++)
    {
        if(a[i]>m)
        {
            temp=(ll)ceil((a[i]-m)*1.0/(k-1));
            num+=temp;
        }
        if(num>m) return false;
    }
    return true;
}
int main()
{
    scanf("%lld",&n);
    ll ma=-INF;
    for(int i=1;i<=n;i++)
    {
        scanf("%lld",&a[i]);
        ma=max(ma,a[i]);
    }
    scanf("%lld",&k);
    if(k==1)
    {
        printf("%lld\n",ma);
        return 0;
    }
    ll l=1,r=1e9;
    ll ans;
    while(r-l>=0)
    {
        ll mid=(l+r)>>1;
        if(judge(mid))
        {
            ans=mid;
            r=mid-1;
        }
        else
            l=mid+1;
    }
    printf("%lld\n",ans);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章