编程语言:Java
题目:
题解:超时了一个极端的测试点,完全可以为其写一个特殊的处理过程,但是我看了一下其他c++写的程序,好像没有处理也过了,于是不想写了。(不是我的错~)
结果:PAC(测试点3 TL)
import java.io.*;
import java.util.*;
public class Main {
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static Scanner sc = new Scanner(new BufferedInputStream(System.in));
static String[] codes;
static int n;
public static void main(String[] args) throws IOException {
n = sc.nextInt();sc.nextLine();
//map用来存储每个字符及其出现的频次
Map<Character, Integer> map = new LinkedHashMap<>();
//优先队列用来构建哈夫曼树
PriorityQueue<TNode> que = new PriorityQueue<TNode>(new Comparator<TNode>() {
@Override
public int compare(TNode o1, TNode o2) {
return o1.num - o2.num;
}
});
//输入初始状态
String[] str = sc.nextLine().split(" ");
for (int i = 0; i < n; i++) {
char ch = str[i * 2].charAt(0);
int num = Integer.parseInt(str[i * 2 + 1]);
map.put(ch, num);
que.add(new TNode(ch, num, null, null));
}
//构建哈夫曼树
TNode root = createHuffmanTree(que);
//根据哈夫曼树的根结点计算WPL
int tar = getHuffmanWeight(root, 1);
//开始对m组数据进行验证
int m = sc.nextInt();sc.nextLine();
codes = new String[n];
while (m-- > 0) {
//sum用来存储该编码策略的WPL,如果不是最小编码长度直接退出
int sum = 0;
for (int i = 0; i < n; i++) {
str = sc.nextLine().split(" ");
codes[i] = str[1];
sum += map.get(str[0].charAt(0)) * str[1].length();
}
//将编码按照字典序进行排列
Arrays.sort(codes, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() == o2.length()) {
return o1.compareTo(o2);
} else {
return o1.length() - o2.length();
}
}
});
if (sum == tar && checkCode()) {
out.println("Yes");
} else {
out.println("No");
}
}
out.flush();
}
//测试该编码策略是否为前缀码
private static boolean checkCode() {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (codes[j].startsWith(codes[i])) {
return false;
}
}
}
return true;
}
//计算哈夫曼树的WPL
private static int getHuffmanWeight(TNode root, int step) {
int res = 0;
if (root.left != null) {
if (root.left.data != '&') {
res += root.left.num * step;
} else {
res += getHuffmanWeight(root.left, step + 1);
}
}
if (root.right != null) {
if (root.right.data != '&') {
res += root.right.num * step;
} else {
res += getHuffmanWeight(root.right, step + 1);
}
}
return res;
}
//构建哈夫曼树
private static TNode createHuffmanTree(PriorityQueue<TNode> que) {
while (que.size() != 1) {
TNode x1 = que.poll();
TNode x2 = que.poll();
que.add(new TNode('&', x1.num + x2.num, x1, x2));
}
return que.poll();
}
}
class TNode {
char data;
int num;
TNode left;
TNode right;
public TNode(char data, int num, TNode left, TNode right) {
this.data = data;
this.num = num;
this.left = left;
this.right = right;
}
}