-
哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和。
-
输入有多组数据。
每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。 -
输出权值。
-
5 1 2 2 5 9
-
37
-
题目描述:
-
输入:
-
输出:
-
样例输入:
-
样例输出:
优先级队列的使用:
import java.util.Scanner;
import java.io.IOException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.lang.Comparable;
import java.util.PriorityQueue;
class Main
{
public static final boolean DEBUG = false;
static class Node implements Comparable<Node>
{
Node parent, left, right;
int w;
Node(Node p, Node l, Node r, int w) {
parent = p;
left = l;
right = r;
this.w = w;
}
public int compareTo(Node other) {
return w - other.w;
}
}
public static int dfs(Node node, int depth)
{
if (node.left == null && node.right == null) {
return depth * node.w;
} else {
return dfs(node.left, depth + 1) + dfs(node.right, depth + 1);
}
}
public static void main(String[] args) throws IOException
{
Scanner cin;
int n;
if (DEBUG) {
cin = new Scanner(new FileReader("e:\\uva_in.txt"));
} else {
cin = new Scanner(new InputStreamReader(System.in));
}
while (cin.hasNext()) {
n = cin.nextInt();
if (n == 1) {
int w = cin.nextInt();
System.out.println(w);
continue;
}
PriorityQueue<Node> pq = new PriorityQueue<Node>();
for (int i = 0; i < n; i++) {
int w = cin.nextInt();
Node tmp = new Node(null, null, null, w);
pq.add(tmp);
}
Node root = null;
while (!pq.isEmpty()) {
if (pq.size() == 1) {
root = pq.poll();
} else {
Node tmp1 = pq.poll();
Node tmp2 = pq.poll();
Node res = new Node(null, tmp1, tmp2, tmp1.w + tmp2.w);
tmp1.parent = res;
tmp2.parent = res;
pq.add(res);
}
}
System.out.println(dfs(root, 0));
}
}
}
166

被折叠的 条评论
为什么被折叠?



