每次挑出权重最小的两组树,将他们进行合并,再将合并过后的树添加到优先队列中,直到队列只剩一棵树
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
//创建节点
class Node{
int weight,size;
Node parent,lchild,rchild;
public Node getLchild() {
return lchild;
}
public void setLchild(Node lchild) {
this.lchild = lchild;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public Node getRchild() {
return rchild;
}
public void setRchild(Node rchild) {
this.rchild = rchild;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
//创建哈树
class Huffman{
//用来存储节点
PriorityQueue<Node>q=new PriorityQueue<>(new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
if(o1.weight==o2.weight){
return o2.size-o1.size;
}
return o1.weight-o2.weight;
}
});
int sum=0;
//添加节点到队列中
public void addNode(Node n){
// System.out.println(n.weight);
q.add(n);
}
//每次选择最小的两棵树进行合并
public void select(){
while(q.size()>1){
Node t1=q.poll(),t2=q.poll();
// System.out.println(t1.weight+" "+t2.weight);
Node tt=new Node();
tt.size+=2;
tt.weight=t1.weight+t2.weight;
tt.lchild=t1;tt.rchild=t2;
t1.parent=tt;t2.parent=tt;
q.add(tt);
}
}
//得到每个叶子的哈夫曼编码
public void Huffmancode(Node root,String s){
if(root.lchild==null&&root.rchild==null){
System.out.println(root.weight+":"+s);
return;
}
if(root.lchild!=null)Huffmancode(root.lchild,s+"0");
if(root.rchild!=null)Huffmancode(root.rchild,s+"1");
}
//用来求权重和
public void Huffmanweight(Node root,int cnt){
if(root.lchild==null&&root.rchild==null) {
sum+=root.weight*cnt;
return;
}
if(root.rchild!=null)Huffmanweight(root.rchild,cnt+1);
if(root.lchild!=null)Huffmanweight(root.lchild,cnt+1);
}
public void print(){
System.out.println(sum);
}
}
public class Main {
public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
int n=cin.nextInt();
Huffman ht=new Huffman();
while(n-->0){
int x=cin.nextInt();
Node tt=new Node();
tt.weight=x;
ht.addNode(tt);
}
ht.select();
Node t=ht.q.poll();
ht.Huffmancode(t,"");
ht.Huffmanweight(t,0);
ht.print();
}
}