关于哈夫曼编码与哈夫曼树的介绍,可以看这个视频
题目链接
以3,4,5,6为例构造哈夫曼树
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
PriorityQueue<Long> heap = new PriorityQueue<>();
while(n-- != 0) {
long x = in.nextLong();
heap.offer(x);
}
//构建哈夫曼树
long ret = 0;
while(heap.size() > 1) {
long t1 = heap.poll();
long t2 = heap.poll();
heap.offer(t1 + t2);
ret += t1 + t2;
}
System.out.print(ret);
}
}