二分法
用一组绳子的长度分别除以最长绳子的一半,如果得到的绳子总和小于目标,那么就减小每个单位的长度right = mid
,反之,增加每个单位的长度left = mid
,当left和right的差值在接近0的某个范围的时候,停止循环。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int target = in.nextInt();
int[] strings = new int[n];
int max = 0;
for (int i = 0; i < n; i++) {
strings[i] = in.nextInt();
if (strings[i] > max) max = strings[i];
}
double res = binarySearch(strings, 0.0, max, target);
System.out.println(res);
}
public static double binarySearch(int[] strings, double left, double right, int target) {
while (Math.abs(left - right) > 1e-6) {
double mid = (left + right) / 2;
int count = 0;
for (int len : strings) {
count += (int) (len / mid);
}
if (count < target) {
right = mid;
} else {
left = mid;
}
}
return left;
}
}
import java.util.Scanner;
public class Changes {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int cost = in.nextInt();
in.close();
int remaining = 1024 - cost;
int res = 0;
int[] changes = {64, 16, 4, 1};
for (int i = 0; i < changes.length; i++) {
res += remaining / changes[i];
remaining = remaining % changes[i];
}
System.out.println(res);
}
}