Drying<二分,思维题>

来源:互联网 发布:淘宝客服的服务用语 编辑:程序博客网 时间:2024/05/20 23:57
Drying
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 16728 Accepted: 4238

Description

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).

Output

Output a single integer — the minimal possible number of minutes required to dry all clothes.

Sample Input

sample input #132 3 95sample input #232 3 65

Sample Output

sample output #13sample output #22

Source

Northeastern Europe 2005, Northern Subregion

题目听了青龙(肖鹏)大佬的讲解才会做,其实关键代码就只有一句公式的推导,其他的就是用二分来做就是了
设吹风机使用的时间为x 二分传进来的时间为mid ,则
x*k+(mid-k)>=a[i],a[i]为当前衣服的水量 ,只有满足这个不等式时,衣服才能烘干
所以x—>(a[i]-mid)/(k-1),又因为x要为整数,所以x需向上取整
用到一个好套路 向上取整 (a+b-2)/(b-1),所以x取(a[i]-mid+k-2)/(k-1),
判断所有衣物吹风机使用的时间之和,如果超过了当前传进来的mid说明,mid偏小,l右移;
#include<cstdio>#include<algorithm>using namespace std;int a[1000005];int n,k;int f(int mid){    int sum=0;   /* if(k==1)        return 1;*/    for(int i=0;i<n;i++)    {        if(a[i]>mid)            sum+=(a[i]-mid+k-2)/(k-1);            if(sum>mid)                return 1;    }    return 0;}int main (){    while(~scanf("%d",&n)){        for(int i=0;i<n;i++)        scanf("%d",&a[i]);        sort(a,a+n);        scanf("%d",&k);        if(k==1)        {            printf("%d\n",a[n-1]);            continue;        }        int l=1,r=a[n-1],ans;        while(l<=r){            int m=(r-l)/2+l;            if(f(m)) l=m+1;            else{                    ans=m;                    r=m-1;                }        }        printf("%d\n",ans);    }    return 0;}