输入n个字符以及它的频率,输出对应的Huffman编码。
样例输入:
6
a,45
b,13
c,12
d,16
e,9
f,5
样例输出:
a:0
c:100
b:101
f:1100
e:1101
d:111
import java.util.ArrayList;
import java.util.Collections;
class Node implements Comparable<Node>{
String val;
int weight;
Node left;
Node right;
public int compareTo(Node node) {
if(this.weight>node.weight)
return 1;
else if(this.weight<node.weight)
return -1;
else
return 0;
}
}
public class Main {
public static void traverse(Node node,String path){
if(node.left==null&&node.right==null){
System.out.println(node.val+":"+path);
return;
}
if(node.left!=null){
traverse(node.left,path+"0");
}
if(node.right!=null){
traverse(node.right,path+"1");
}
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext())
{
int n=scanner.nextInt();
scanner.nextLine();
ArrayList<Node> list=new ArrayList<Node>();
for(int i=0;i<n;i++){
String str=scanner.nextLine();
String[] arr=str.split(",");
Node node=new Node();
node.val=arr[0];
node.weight=Integer.parseInt(arr[1]);
list.add(node);
}
while(list.size()>1){
Collections.sort(list);
Node node=new Node();
Node n1=list.get(0);
Node n2=list.get(1);
node.left=n1;
node.right=n2;
node.weight=n1.weight+n2.weight;
list.remove(0);
list.remove(0);
list.add(node);
}
Node root=list.get(0);
traverse(root,"");
}
scanner.close();
}
}