2025-07-25 22:02:47 +09:00

42 lines
1.1 KiB
C

#include <stdio.h>
#include <stdlib.h>
long long cutTree(const int* tree, int treeNum, int cuttingHeight);
int main(){
int N, M;
scanf("%d %d",&N, &M);
int* tree = (int*)malloc(sizeof(int)*N);
int maxHeight = 0;
for(int i=0; i<N; i++){
scanf("%d",&tree[i]);
if(maxHeight<tree[i]) maxHeight = tree[i];
}
int start = 0, end = maxHeight;
int optimalHeight = 0;
while(start <= end){
int midHeight = start + (end - start) / 2; // (start + end) / 2 의 오버플로우 방지 형태
long long cutAmount = cutTree(tree,N,midHeight);
if(cutAmount<M) end = midHeight - 1;
else {
optimalHeight = midHeight;
start = midHeight + 1;
}
}
printf("%d\n",optimalHeight);
free(tree);
return 0;
}
long long cutTree(const int* tree, int treeNum, int cuttingHeight) {
long long totalCut = 0;
for(int i = 0; i < treeNum; i++){
if (tree[i] > cuttingHeight) {
totalCut += tree[i] - cuttingHeight;
}
}
return totalCut;
}