1题目:Huffman Codes
http://www.patest.cn/contests/mooc-ds/04-3
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.util.ArrayList; 5 import java.util.Collections; 6 import java.util.HashMap; 7 import java.util.List; 8 import java.util.Map; 9 import java.util.PriorityQueue; 10 import java.util.Queue; 11 12 public class Main { 13 public static void main(String args[]) throws NumberFormatException, 14 IOException { 15 BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 16 int N = Integer.parseInt(in.readLine()); // 存储键值对的个数 17 String[] line = in.readLine().split(" "); 18 Map<String, Integer> map = new HashMap<String, Integer>();// 存储A 1 B 1 C 19 // 1 D 3 E 3 20 // F 6 G 21 // 6的键值对 22 Queue<Integer> priorityQueue = new PriorityQueue<Integer>(N);// 使用优先级列队模拟堆 23 24 for (int i = 0; i < N; i++) { 25 map.put(line[2 * i], Integer.parseInt(line[2 * i + 1])); 26 priorityQueue.add(Integer.parseInt(line[2 * i + 1])); 27 } 28 /* 计算Wpl的值 */ 29 int Wpl = 0; 30 while (!priorityQueue.isEmpty()) { 31 int top1 = priorityQueue.poll(); 32 if (!priorityQueue.isEmpty()) { 33 int top2 = priorityQueue.poll(); 34 int temp = top1 + top2; 35 priorityQueue.add(temp); 36 Wpl += temp; 37 } 38 } 39 // 输入测试数据 40 41 int CheckN = Integer.parseInt(in.readLine()); 42 for (int i = 0; i < CheckN; i++) { 43 Test[] test = new Test[N]; 44 int wpl2 = 0; 45 String[] read; 46 List<Test> array = new ArrayList<Test>(); 47 for (int j = 0; j < N; j++) { 48 read = in.readLine().split(" "); 49 test[j] = new Test(); 50 test[j].a = read[0]; 51 test[j].s = read[1]; 52 array.add(test[j]); 53 wpl2 += read[1].length() * map.get(read[0]); 54 } 55 Collections.sort(array); 56 if (Wpl != wpl2) { 57 System.out.println("No"); 58 continue; 59 } else { 60 boolean flag = true; 61 for (int n = 0; n < N - 1; n++) { 62 String tmp = array.get(n).s; 63 for (int m = n + 1; m < N; m++) { 64 if (array.get(m).s.substring(0, tmp.length()).equals( 65 tmp)) { 66 flag = false; 67 } 68 } 69 } 70 if (flag) { 71 System.out.println("Yes"); 72 } else { 73 System.out.println("No"); 74 } 75 } 76 77 } 78 79 } 80 81 } 82 83 class Test implements Comparable { 84 String a; 85 String s; 86 87 public String getA() { 88 return a; 89 } 90 91 public void setA(String a) { 92 this.a = a; 93 } 94 95 public String getS() { 96 return s; 97 } 98 99 public void setS(String s) { 100 this.s = s; 101 } 102 103 @Override 104 public int compareTo(Object o) { 105 // TODO Auto-generated method stub 106 return this.s.length() - ((Test) o).s.length(); 107 } 108 }