题目链接:Saving HDU
这题是个背包问题,首先按照单价排序,然后,装的下就装,装不下就分割。
import java.util.Scanner;//背包问题
public class Main{private static Scanner scanner;private static int pi[];private static int mi[];public static void main(String[] args) {scanner = new Scanner(System.in);while (scanner.hasNext()) {int v = scanner.nextInt();// 容量if (v == 0) {break;}int n = scanner.nextInt();// 宝贝种类pi = new int[n];// 单价mi = new int[n];// 体积for (int i = 0; i < n; i++) {pi[i] = scanner.nextInt();mi[i] = scanner.nextInt();}// 按照单价排序sort();// for (int i = 0; i < n; i++) {// System.out.println(pi[i]+","+mi[i]);// }int sum = 0;// 总价值for (int i = 0; i < n; i++) {if (mi[i] >= v) {// 来到这里就一定可以装满sum += v * pi[i];break;} else {sum += pi[i] * mi[i];v -= mi[i];// v重新表示为:背包剩余容量}}System.out.println(sum);}}private static void sort() {for (int i = 0; i < pi.length - 1; i++) {for (int j = i + 1; j < pi.length; j++) {if (pi[i] < pi[j]) {int temp = pi[i];pi[i] = pi[j];pi[j] = temp;temp = mi[i];mi[i] = mi[j];mi[j] = temp;}}}}
}