题目描述
注意
h[i]和w[i]取值范围为1~10E5,当边长为1时,h[i]*w[i]可能会超过int范围,存在溢出问题。因此需取long型。
二分法
import java.util.Scanner;
/**
* @author JohnnyLin
* @version Creation Time:2021年1月17日 下午5:34:48
* 类说明
*/
public class Main {
static final int N = 100010;
static long h[] =new long[N];
static long w[] =new long[N];
static int n,k;
public static boolean check(int t) {
long res = 0;
for(int i = 0; i < n; i++){
res += (h[i]/t)*(w[i]/t);
if (res >= k) return true;
}
return false;
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
n = reader.nextInt();
k = reader.nextInt();
for(int i = 0; i < n; i++) {
h[i] =reader.nextInt();
w[i]=reader.nextInt();
}
long area = 0;
//预处理
for(int i = 0; i < n; i++) {
area += h[i]*w[i];
}
//边长的最大可能取值
long t = area/k;
int l = 1, r =(int) Math.sqrt(t)+1;
// 区间[l, r]被划分成[l, mid - 1]和[mid, r]时使用:
while(l < r) {
int mid = l+r+1>>1;
if(check(mid)) l = mid;
else r = mid - 1;
}
System.out.println(l);
return;
}
}
关于二分可阅读下面文 基础算法一:二分法,你思考过这些问题吗?