哈夫曼树
哈夫曼树,第一行输入一个数n,表示叶结点的个数,第二行输入各个叶子结点的权值。
需要用这些叶结点生成哈夫曼树,题目需要输出哈夫曼树的带权路径长度(WPL)。
输入格式:
第一行输入一个数n,第二行输入n个叶结点的权值(叶结点权值不超过1000,2<=n<=1000)。
输出格式:
在一行中输出WPL值。
输入样例:
5
1 2 2 5 9
输出样例:
37
首先我们先获取从键盘中输入的数值,然后再将所获取的数值放进ArrayList中,最后调用hafu()方法,代码如下所示:
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()){
int n = sc.nextInt(); //需要多少个叶子结点
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < n ; i++) {
int x = sc.nextInt(); //叶子结点的数值
list.add(x);
}
System.out.println(hafu(list));
}
hafu()方法首先将ArrayList列表进行排序,如果list的大小等于两个的时候直接返回列表的第一个数和第二个数,最后再通过return统计总数。代码如下所示:
public static int hafu(ArrayList<Integer> list) {
Collections.sort(list); //list列表可以通过 Collections.sort进行排序
if(list.size() == 2) return list.get(0) + list.get(1);
int a = list.remove(0);
int b = list.remove(0);
int n = a + b;
list.add(n);
return a + b + hafu(list); //进行统计
}
流程图如下图所示:
结果图:
最后完整的代码如下所示:
import java.util.*;
public class HuFu {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()){
int n = sc.nextInt(); //需要多少个叶子结点
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < n ; i++) {
int x = sc.nextInt(); //叶子结点的数值
list.add(x);
}
System.out.println(hafu(list));
}
}
public static int hafu(ArrayList<Integer> list) {
Collections.sort(list); //list列表可以通过 Collections.sort进行排序
if(list.size() == 2) return list.get(0) + list.get(1);
int a = list.remove(0);
int b = list.remove(0);
int n = a + b;
list.add(n);
return a + b + hafu(list); //进行统计
}
}