Greedy algorithm-drying clothes problem

Existing n pieces of clothes need to be dried, and the moisture content of each piece of clothing is ai. If it is dried naturally, the moisture content will decrease by 1 per minute; if the dryer is used for drying, the moisture content will decrease by k (until 0). There is only one dryer, which can only dry one piece of clothing at a time, and use it for at least 1 minute at a time. What is the minimum time to make all the clothes water content 0?

#include<stdio.h>
#include<cmath>
#include<algorithm>
using namespace std;

const int MAXN = 1e5+10;
int water[MAXN];

//判断在时间time内是否可以将所有衣服烘干 
bool judge(int n,int k,int time){
    
    
	int sum = 0;
	for(int i = 0;i < n; ++i){
    
    
		if(water[i] > time){
    
    
			sum += ceil((water[i] - time)*1.0 / (k-1));
		} 
		if(sum > time)
			return false;
	}
	return true;
}

int main()
{
    
    
	int n;
	scanf("%d",&n);
	for(int i = 0;i < n; ++i){
    
    
		scanf("%d",&water[i]);
	} 
	int k;
	scanf("%d",&k);
	sort(water,water+n);
	if(k == 1)
		printf("%d\n",water[n-1]);
	else{
    
    
		//二分法找满足条件的最小值 
		int left = 1;
		int right = water[n-1];
		while(left <= right){
    
    
			int middle = left + (right - left)/2;
			if(judge(n,k,middle)){
    
    
				right = middle - 1;
			}
			else{
    
    
				left = middle + 1;
			}
		} 
		printf("%d",left);
		
	}
	return 0;	
} 

Guess you like

Origin blog.csdn.net/Gentle722/article/details/113096839