航电 1009 JAVA
http://acm.hdu.edu.cn/showproblem.php?pid=1009
其实就是简单的贪心问题,但是我的代码却老是WA,弄了一晚上,找不出原因,希望高手给分析一下。谢谢!
import java.util.Comparator;import java.util.Scanner;/** * @author wensefu * @hdoj 1009 * @date 10-4-19 */class Element { public Element(int i, double bean, double food) { this.i = i; this.bean = bean; this.food = food; } int i; double food; double bean;}public class Main { /** * 核心函数 * * @param * m FOOD总量 * @param * f FOOD * @param * b BEAN * @return 最大价值 */ public static double getBean(double m, double[] f, double[] b) { int n = f.length; Element[] d = new Element[n]; for (int i = 0; i < n; i++) { d[i] = new Element(i, b[i], f[i]); } sort(d); int i; float bean = 0; i = 0; while (i < n && m >= d[i].food) { bean += d[i].bean; m -= d[i].food; i++; } if (i < n && m >= 0) { bean += d[i].bean * m / d[i].food; } return bean; } /** * 按单位价值非递减排序 * * @param e */ @SuppressWarnings("unchecked") public static void sort(Element[] e) { java.util.Arrays.sort(e, new Comparator() { public int compare(Object o1, Object o2) { Element e1 = (Element) o1; Element e2 = (Element) o2; return Double.compare(e2.bean / e2.food, e1.bean / e1.food); } }); } /** * @param args */ public static void main(String[] args) { Scanner cin = new Scanner(System.in); double[] f = new double[1001]; /* weight */ double[] j = new double[1001]; /* value */ while (true) { int m = 0, n = 0; /* m->c */ for (int i = 0; i < f.length; i++) f[i] = 0; for (int i = 0; i < j.length; i++) j[i] = 0; m = cin.nextInt(); n = cin.nextInt(); if (m == -1 && n == -1) return; for (int i = 0; i < n; i++) { j[i] = cin.nextDouble(); f[i] = cin.nextDouble(); } double maxBean = getBean(m, f, j); System.out.printf("%.3f\n", maxBean); } }}