import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int n = scanner.nextInt(); List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(scanner.nextInt()); } int minCost = 0; while (list.size() != 1) { minCost += getCost(list); } System.out.println(minCost); } } private static int getCost(List<Integer> list) { int min1 = getMin(list); int min2 = getMin(list); int cost = min1 + min2; list.add(cost); return cost; } private static int getMin(List<Integer> list) { int min = list.get(0); for (int i = 1; i < list.size(); i++) { if (min > list.get(i)) { min = list.get(i); } } list.remove((Object) min); return min; } }
[BASIC-28] Huffuman树,布布扣,bubuko.com
原文:http://blog.csdn.net/u011506951/article/details/26703939