package demo;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
public class MyHuffman {
PriorityQueue<Node> nodeList = null;//节点List
//根节点
Node root = null;
ArrayList<String> list = null;
public MyHuffman() {
nodeList = new PriorityQueue<Node>(new Comparator<Node>() {
public int compare(Node o1, Node o2) {
return o1.weight-o2.weight;
};
});//节点List
root = new Node();
list = new ArrayList<String>();
}
public void creatHuffman() {
while(nodeList.size()>1) {
Node left = nodeList.poll();
Node right = nodeList.poll();
Node node = new Node( left.weight+right.weight, "", left, right);
buquan(node);
nodeList.add(node);
}
root = nodeList.poll();
}
public void jiema(String str) {
jiema(root,str);
}
public void jiema(Node node,String str) {
if(node.data.equals(str)){
list.add(node.code);
}
if(node.lChild !=null) {
jiema(node.lChild,str);
}
if(node.rChild !=null) {
jiema(node.rChild,str);
}
}
public void buquan(Node node) {
if(node.lChild !=null) {
node.lChild.code = node.code+"0";
buquan(node.lChild);
}
if(node.rChild !=null) {
node.rChild.code = node.code+"1";
buquan(node.rChild);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = Integer.valueOf(sc.nextLine());
MyHuffman myhuffman = new MyHuffman();
while(count-->0) {
String[] str = sc.nextLine().split(" ");
Node node = new Node(str[0],Integer.valueOf(str[1]));
myhuffman.nodeList.add(node);
}
myhuffman.creatHuffman();
String input = sc.nextLine();
for(int i=0;i<input.length();i++) {
myhuffman.jiema(myhuffman.root,input.charAt(i)+"");
}
for(String out:myhuffman.list) {
System.out.print(out);
}
}
}
class Node{
//哈夫曼编码
String code = "";
//权重
int weight;
//数据
String data = "";
Node lChild;
Node rChild;
public Node() {
}
public Node(String data, int weight) {
super();
this.weight = weight;
this.data = data;
}
public Node(int weight, String data, Node lChild, Node rChild) {
super();
this.weight = weight;
this.data = data;
this.lChild = lChild;
this.rChild = rChild;
}
}
输入 格式
位数
值 权重
字符串