今天在刷题时,遇到了一个huffman树问题,把问题记录下来。
题目描述
哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和。
代码是这样写的
输入描述:
输入有多组数据。 每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。
输出描述:
输出权值。
输入例子:
5 1 2 2 5 9
输出例子:
37
import java.util.Scanner;
import java.util.LinkedList;
import java.util.Collections;
class Treenodex
{
int weight;
Treenodex left;
Treenodex right;
Treenodex parent;
Treenodex(int weight)
{
this.weight = weight;
}
}
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
while(sc.hasNext())
{
int n = sc.nextInt();
LinkedList<Integer> list = new LinkedList<Integer>();
for(int i=0;i<n;i++)
{
list.add(sc.nextInt());
}
Collections.sort(list);
Treenodex root = null;
int result = 0;
while(list.size()!=0)
{
int a = list.removeFirst();
int b = list.removeFirst();
result+=a+b;
Treenodex t1 = new Treenodex(a);
Treenodex t2 = new Treenodex(b);
Treenodex t3 = new Treenodex(a+b);
t1.parent = t3;
t2.parent = t3;
t3.left = t1;
t3.right = t2;
if(!list.isEmpty())
list.add(a+b);
else
root = t3;
Collections.sort(list);
}
System.out.println(result);
}
}
}
可以在构造huffman树的过程中统计节点的权值和。