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 kthis 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 #1
3
2 3 9
5
sample input #2
3
2 3 6
5
Sample Output
sample output #1
3
sample output #2
2
題目大意不多說,主要說說 思想 。 剛開始做這道題時,就卡了好久,好不容易 想出辦法 ,結果 提交 後 TLE ,哎,最後 還是 上網 搜了一下 大神們的 解題報告 ,才知道此題需用 二分 ,不得不感歎 大神們 的智慧啊 !! 以下說說本人的見解, 此題的思路是:二分 時間 ,假設 時間 為 t,那麼含水量小於或等於 t 的衣服直接風干就行了,不需考慮,設含水量大於 t 的第i件衣服所帶的 水量 為Ai ,需要用 吹風機的 次數 為 X ,用於 風干 的時間為 Y,吹風機一分鐘 能夠 吹干的水量為 k,則 可得到 以下兩式 : X + Y = t ; X + Y * k >= Ai ; 由以上兩式可得 : Y >= (Ai - t)/(k - 1) 算出所有含水量大於 t 的衣服 的 最小的 Y , 然後相加得到 sum ,再用 sum 與 t 比較 ,作為 二分中 上下界改變的條件 。具體用法的 詳解 請看程序:
[cpp
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
long long a[100005]; // 注意 : 此題 需用 long long ,用 int 會 WA !!
int main()
{
int n;
scanf("%d",&n);
int i;
long long max = -1;
for(i=1; i<=n; i++)
{
scanf("%lld",&a[i]);
if(max < a[i]) // 找出 含水量的最大值
max = a[i];
}
long long k ;
scanf("%lld",&k);
if (k == 1) //k == 1 的情況 需要單獨判斷 !!!
{
printf("%lld\n",max);
}
else
{
long long left = 1,right = max,mid; // 用含水量的最大值 作為 上邊界
while (right > left)
{
mid = (left + right)/2;
int j ;
long long sum =0;
for(j=1; j<=n; j++)
{
if(a[j] > mid)
{
long long tmp = ceil((a[j]-mid) * 1.0 / (k-1)); // ceil 是 向上取整 的函數
sum += tmp;
} www.2cto.com
}
if(sum > mid) // 此處 是 ">" , 不要寫成 ">=" !!
{
left = mid + 1;
}
else
{
right = mid; // WA 了無數次 原來 是這裡出錯了,可千萬不能寫成 right = mid - 1 !!!!
}
}
mid = ( right + left )/2;
printf("%lld\n",mid);
}
return 0;
}