哈夫曼树的概念见另一篇博客点击打开链接,代码如下
package Tree;
import java.io.BufferedInputStream;
import java.util.*;
public class Huffman {
static Comparator myComparator = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if((int)o1>(int)o2) return 1;
else if((int)o1==(int) o2) return 0;
else return -1;
}
};
static PriorityQueue<Integer> Q = new PriorityQueue<Integer>(myComparator);
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(new BufferedInputStream(System.in));
while(sc.hasNext()) {
n = sc.nextInt();
for(int i = 0;i<n;i++) {
int tmp = sc.nextInt();
Q.add(tmp);
}
int ans = 0;
while(Q.size()>1) {
int a = Q.poll();
int b = Q.poll();
ans+=a+b;
Q.add(a+b);
}
System.out.println(ans);
}
}
}