大家好,我是爬行系,今天打卡的题和昨天的题差不多,都考查了整数二分。
题目描述
题目描述
木材厂有 n 根原木,现在想把这些木头切割成 k 段长度均为 l 的小段木头(木头有可能有剩余)。
当然,我们希望得到的小段木头越长越好,请求出 l 的最大值。
木头长度的单位是 cm,原木的长度都是正整数,我们要求切割得到的小段木头的长度也是正整数。
例如有两根原木长度分别为 11 和 21,要求切割成等长的 6 段,很明显能切割出来的小段木头长度最长为 5。
输入格式
第一行是两个正整数 n,k,分别表示原木的数量,需要得到的小段的数量。
接下来 n 行,每行一个正整数 L,表示一根原木的长度。
输出格式
仅一行,即l的最大值。
如果连1cm 长的小段都切不出来,输出 0。
题目链接
解题思路
题目要求切割出来的每小段木块长度 l 的最大值,且是有序的,我们就可以想到用二分法,题目中允许木头有剩余,就可以确定下 l 可取的最大值high等于所有原木长度的最大值。只要low=0,high=maxlen确定下来,当low<high,判断每个二分mid时,原木实际可以切割出多少小段木头,当check(mid)>=k时,说明小段木头的长度可以在大点,low=mid;反之,说明小段木头的长度太大了,切割得到的小木段数不足k,则high=mid-1。
AC代码
import java.io.*;
public class Main {
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static StreamTokenizer st=new StreamTokenizer(br);
static int n,k;
static int[] len=new int[100005];
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
n=nextInt();
k=nextInt();
int maxlen=Integer.MIN_VALUE;
for(int i=0;i<n;i++) {
len[i]=nextInt();
if(len[i]>maxlen) {
maxlen=len[i];
}
}
int low=0,high=maxlen;
while(low<high) {
int mid=(low+high+1)/2;
if(check(mid)>=k) {
low=mid;
}else {
high=mid-1;
}
}
System.out.println(high);
}
public static int check(int mid) {
int count=0;
for(int i=0;i<n;i++) {
count+=len[i]/mid;
}
return count;
}
public static int nextInt() throws IOException {
st.nextToken();
return (int)st.nval;
}
}