北京邮电大学 哈夫曼树(java)

题目描述
哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和。
输入描述:
输入有多组数据。
每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。
输出描述:
输出权值。
示例1
输入
复制
5  
1 2 2 5 9
输出
复制
37
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.* ;
public class Main
{
	public static void main(String[] args) {
	    try {
	        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	        String str;
	        while((str = br.readLine()) != null) {
	        	int n = Integer.parseInt(str);
	        	String[] parts = br.readLine().split(" ");
	        	ArrayList<Integer> list = new ArrayList<>();
	        	for(int i = 0; i < n; i++) {
	        		list.add(Integer.parseInt(parts[i]));
	        	}
	        	System.out.println(hafu(list));
	        }
	        	
	    } catch(IOException e) {
	    	e.printStackTrace();
	    }
	}
	public static int hafu(ArrayList<Integer> list) {
		Collections.sort(list);
		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);
	}
}



发布了231 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43306331/article/details/104229559