1. 程式人生 > >POJ 3104 Drying(二分答案)

POJ 3104 Drying(二分答案)

cap esp aci tel pad this 需要 har ssi

Drying
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 24089   Accepted: 6031

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 kwater, 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

Source

Northeastern Europe 2005, Northern Subregion

【題意】

有一些衣服,每件衣服有一定水量,有一個烘幹機,每次可以烘一件衣服,每分鐘可以烘掉k滴水。每件衣服沒分鐘可以自動蒸發掉一滴水,用烘幹機烘衣服時不蒸發。問最少需要多少時間能烘幹所有的衣服

【分析】

二分答案。但需註意:

①每分鐘烘幹k單位的水,於是我就想當然地除k向上取整了((aimid) / k)。其實應該除以k-1,列個詳細的算式:

設需要用x分鐘的機器,那麽自然風幹需要mid x分鐘,xmid需要滿足:

k*x + (mid x) >=ai,即 x >= (aimid) / (k 1)

②當k=1的時候,很顯然會發生除零錯誤,需要特殊處理

【代碼】

#include<cstdio>
#include<algorithm>
#include<iostream>
#define debug(x) cerr<<#x<<" "<<x<<‘\n‘;
using namespace std;
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();}
    while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();}
    return x*f;
}
const int N=1e5+5;
int ans,n,k,d[N];
inline bool check(int now){
	int res=0;
	for(int i=1;i<=n;i++){
		int left=d[i]-now;
		if(left>0){
			res+=(left+k-1)/k;
			if(res>now) return 0;
		}
	}	
	return 1;
}
int main(){
	n=read();
	for(int i=1;i<=n;i++) d[i]=read();
	k=read();k--;
	sort(d+1,d+n+1);
	if(!k){printf("%d\n",d[n]);return 0;}
	int l=0,r=d[n],mid;
	while(l<=r){
		mid=l+r>>1;
		if(check(mid)){
			ans=mid;
			r=mid-1;
		}
		else{
			l=mid+1;
		}
	}
	printf("%d\n",ans);
	return 0;
}

POJ 3104 Drying(二分答案)