HDOJ-1053

原题:http://acm.hdu.edu.cn/showproblem.php?pid=1053

题解

    求字符串压缩后的最短的数据长度,就是哈夫曼树求解WPL问题。构建一颗带权的哈夫曼树,求出WPL。不理解哈夫曼树,可以先看下这篇哈夫曼树以及哈夫曼编码来了解一下。

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;


public class Main {
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		while (true) {
			String str = cin.nextLine();
			if (str.equals("END"))
				break;
			Haffman haffman = new Haffman();
			char ch[] = new char[str.length()];
			for (int i = 0; i < str.length(); i++) {
				ch[i] = str.charAt(i);
			}
			haffman.build(ch);
			int sum = 0;
			for (int i = 0; i < ch.length; i++) {
				sum += haffman.getWeight(ch[i]);
			}
			if(sum == 0) sum = str.length();
			double bili = (double) str.length() * 8 / (double) sum;
			System.out.print(str.length() * 8 + " " + sum + " ");
			System.out.printf("%.1f", bili);
			System.out.println();
		}
	}
}

class HaffmanNode {
	int val; // 值
	int weight;// 权值
	char ch;// 所放字符串
	HaffmanNode left;// 左孩子
	HaffmanNode right;// 右孩子

	public HaffmanNode(int val, char ch) {
		this.val = val;
		this.ch = ch;
	}
}

class Haffman {
	HaffmanNode root;
	int count[] = new int[200];
	public void build(char[] arr) {
		for (int i = 0; i < arr.length; i++) {
			count[arr[i] - 'A']++;
		}
		PriorityQueue<HaffmanNode> priorityQueue = new PriorityQueue<>(new Comparator<HaffmanNode>() {
			public int compare(HaffmanNode o1, HaffmanNode o2) {
				return o1.val - o2.val;
			}
		});
		for (int i = 0; i < count.length; i++) {
			if (count[i] != 0) {
				priorityQueue.offer(new HaffmanNode(count[i], (char) (65 + i)));
			}
		}
		while (priorityQueue.size() != 1) {
			HaffmanNode left = priorityQueue.poll();
			HaffmanNode right = priorityQueue.poll();
			HaffmanNode newHaffmanNode = new HaffmanNode(left.val + right.val, ' ');
			newHaffmanNode.left = left;
			newHaffmanNode.right = right;
			priorityQueue.add(newHaffmanNode);
		}
		root = priorityQueue.poll();
	}
	private Map<Character, Integer> map1 = null;
	private void getWeight() {
		map1 = new HashMap<>();
		count(root, 0);
	}
	public Integer getWeight(char ch) {
		if (map1 == null) {
			getWeight();
		}
		return map1.get(ch);
	}
	public void count(HaffmanNode haffmanNode, int weight) {
		if (haffmanNode != null && haffmanNode.ch != ' ') {
			map1.put(haffmanNode.ch, weight);
		}
		if (haffmanNode.left != null) {
			count(haffmanNode.left, weight + 1);
		}
		if (haffmanNode.right != null) {
			count(haffmanNode.right, weight + 1);
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值