算法游戏:切木棍

m根木棍,通过切削分成n根相同长度的小木棍(m<n),求这n根小木棍的最长长度;
注意:小木棍不可拼接。
public class QieMuGun {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int m = sc.nextInt();
		int n = sc.nextInt();
		double[] a = new double[m];
		for (int i = 0; i < m; i++) {
			a[i] = sc.nextDouble();
		}
		sc.close();
		double value = solve(a, n);
		DecimalFormat df = new DecimalFormat("#.00");
		System.out.println(df.format(value));
	}

	public static double solve(double[] a, int n) {
		sortBiger(a);
		double r = a[0];
		double l = 0.0;
		double m = l / 2;
		while (true) {
			int sum = 0;
			m = (l + r) / 2;
			for (int i = 0; i < a.length; i++) {
				sum += a[i] / m;
			}
			if (sum >= n) {
				l = m;
			} else {
				r = m;
			}
			if (sum == n && (r - l) < 0.001) {
				break;
			}
		}
		return m;
	}

	public static void sortBiger(double[] a) {
		int x;
		double temp;
		for (int i = 0; i < a.length - 1; i++) {
			x = i;
			for (int j = i + 1; j < a.length; j++) {
				if (a[x] > a[j]) {
					x = j;
				}
			}
			if (x != i) {
				temp = a[x];
				a[x] = a[i];
				a[i] = temp;
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值