题目1172:哈夫曼树

题目描述:

哈夫曼树,第一行输入一个数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));
		}
	}
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值