Huffman Codes(java)

7-9 Huffman Codes(30 分)

In 1953, David A. Huffman published his paper "A Method for the Construction of Minimum-Redundancy Codes", and hence printed his name in the history of computer science. As a professor who gives the final exam problem on Huffman codes, I am encountering a big problem: the Huffman codes are NOT unique. For example, given a string "aaaxuaxz", we can observe that the frequencies of the characters 'a', 'x', 'u' and 'z' are 4, 2, 1 and 1, respectively. We may either encode the symbols as {'a'=0, 'x'=10, 'u'=110, 'z'=111}, or in another way as {'a'=1, 'x'=01, 'u'=001, 'z'=000}, both compress the string into 14 bits. Another set of code can be given as {'a'=0, 'x'=11, 'u'=100, 'z'=101}, but {'a'=0, 'x'=01, 'u'=011, 'z'=001} is NOT correct since "aaaxuaxz" and "aazuaxax" can both be decoded from the code 00001011001001. The students are submitting all kinds of codes, and I need a computer program to help me determine which ones are correct and which ones are not.

Input Specification:

Each input file contains one test case. For each case, the first line gives an integer N (2≤N≤63), then followed by a line that contains all the N distinct characters and their frequencies in the following format:

 

c[1] f[1] c[2] f[2] ... c[N] f[N]

where c[i] is a character chosen from {'0' - '9', 'a' - 'z', 'A' - 'Z', '_'}, and f[i] is the frequency of c[i] and is an integer no more than 1000. The next line gives a positive integer M (≤1000), then followed by Mstudent submissions. Each student submission consists of N lines, each in the format:

c[i] code[i]

where c[i] is the i-th character and code[i] is an non-empty string of no more than 63 '0's and '1's.

Output Specification:

For each test case, print in each line either "Yes" if the student's submission is correct, or "No" if not.

Note: The optimal solution is not necessarily generated by Huffman algorithm. Any prefix code with code length being optimal is considered correct.

Sample Input:

7
A 1 B 1 C 1 D 3 E 3 F 6 G 6
4
A 00000
B 00001
C 0001
D 001
E 01
F 10
G 11
A 01010
B 01011
C 0100
D 011
E 10
F 11
G 00
A 000
B 001
C 010
D 011
E 100
F 101
G 110
A 00000
B 00001
C 0001
D 001
E 00
F 10
G 11

Sample Output:

Yes
Yes
No
No

思路:

1、首先自己根据这些字符和频率建立哈夫曼树,求出最小WPL。

2、计算出每个学生编码的WPL,即用字符串的长度乘以频率。

3、用String中的startwith()函数两两判断一个字符串是否是另一个字符串的前缀。当满足前缀码要求并且WPL与哈夫曼计算出的WPL相等时,认为是正确的。

4、建哈夫曼树时,可以利用最小堆(优先队列)输出2个最小的。合并之后再添加到最小堆中。我是直接给数组排序了,没用最小堆。

5、整体思路比较简单,有些坑容易跳,比如,学生输入的字符顺序可能是乱的,甚至字符输入的就不是给定的字符?有两个测试点到现在还是通不过,等9月份再次开课之后再进去试试,看看到底是什么测试点。

 

 

import java.util.Arrays;
import java.util.Scanner;

public class Main {
	private static int sum=0;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();     						//记录总的字符数量
		char [] ch = new char[n];
		int [] fr = new int[n];
		for (int i = 0;i<n;i++) {
			ch[i]=in.next().charAt(0);
			fr[i]=in.nextInt();
		}
		int stu =in.nextInt();
		
		int wpl_min = huffman_code_wpl(fr);
		for(int i = 0;i<stu;i++) {
			judge(in,ch,fr,wpl_min);
		}
		
	}

	private static void judge(Scanner in, char[] ch, int[] fr,int wpl_min) {
		// TODO Auto-generated method stub
		int n = ch.length;
		int wpl=0;
		int flag = 1;
		String code [] = new String[n]; 
		Jiedian root = new Jiedian();

		char xi ;
		
	
		for(int i=0;i<n;i++) {
			xi = in.next().charAt(0);
			code[i]= in.next();	
			int j = 0;
			for(;j<n;j++) {
				if (ch[j]==xi)
					break;
			}
			
			if(j==n)
				flag=0;			
			wpl =wpl+ code[i].length()*fr[j];
		}
		
		for(int i =0;i<n;i++) {
			for(int j = 0;j<n;j++) {
				if(i!=j&&code[i].startsWith(code[j]))
					flag=0;
		}
	}
	
		if (flag ==0||wpl!=wpl_min)
			System.out.println("No");
		else
			System.out.println("Yes");
			
		wpl=0;
		
	}

	private static int huffman_code_wpl( int[] fr) {
		// TODO Auto-generated method stub
		Arrays.sort(fr);
		int n = fr.length;
		
		Jiedian rt =null;
		
		Jiedian [] jd = new Jiedian[n];
		for(int i = 0; i<n ;i++) {
			jd[i] = new Jiedian();
			jd[i].num = fr[i];
		}
		
		for(int i = 0; i<n-1 ; i++) {
			Jiedian root = new Jiedian();
			
			root.left = jd[0];
			root.right = jd[1];
			root.num = jd[0].num+jd[1].num;
			jd[1] = root;
			jd[0] = new Jiedian();
			jd[0].num = Integer.MAX_VALUE;
			
			rt = root;
	
			sort(jd);
		}
		int way = 0;
		traversal(rt,way);
		int wpl = sum;
		sum=0;
		return wpl;

	}

	private static void traversal(Jiedian rt,int way) {
		// TODO Auto-generated method stub
		if(rt==null);
		
		else if(rt.left==null&&rt.right==null) {
			sum=rt.num*way+sum;
		}
		else {
			traversal(rt.left,way+1);		
			traversal(rt.right,way+1);
		}
	}

	private static void sort(Jiedian[] jd) {
		// TODO Auto-generated method stub
		int n =jd.length;
		Jiedian temp = new Jiedian();
		for(int i = 0;i<n;i++) {
			for(int j =i+1; j<n; j++) {
				if(jd[j].num<jd[i].num) {
					temp = jd[i];
					jd[i] = jd[j];
					jd[j] = temp;
				}
			}
		}
	}

}

class Jiedian{
	Jiedian left =null;
	Jiedian right = null;
	String code =null;
	int num = 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
import java.util.*; class HuffmanNode implements Comparable<HuffmanNode> { int frequency; char data; HuffmanNode left, right; public HuffmanNode(int frequency, char data) { this.frequency = frequency; this.data = data; } public boolean isLeaf() { return left == null && right == null; } @Override public int compareTo(HuffmanNode node) { return frequency - node.frequency; } } public class HuffmanCoding { public static void main(String[] args) { String text = "Hello, world!"; Map<Character, Integer> frequencyMap = buildFrequencyMap(text); HuffmanNode root = buildHuffmanTree(frequencyMap); Map<Character, String> huffmanCodes = buildHuffmanCodes(root); System.out.println("Original text: " + text); System.out.println("Huffman codes: " + huffmanCodes); System.out.println("Encoded text: " + encode(text, huffmanCodes)); System.out.println("Decoded text: " + decode(encode(text, huffmanCodes), root)); } private static Map<Character, Integer> buildFrequencyMap(String text) { Map<Character, Integer> frequencyMap = new HashMap<>(); for (char c : text.toCharArray()) { frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1); } return frequencyMap; } private static HuffmanNode buildHuffmanTree(Map<Character, Integer> frequencyMap) { PriorityQueue<HuffmanNode> priorityQueue = new PriorityQueue<>(); for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) { priorityQueue.offer(new HuffmanNode(entry.getValue(), entry.getKey())); } while (priorityQueue.size() > 1) { HuffmanNode left = priorityQueue.poll(); HuffmanNode right = priorityQueue.poll(); HuffmanNode parent = new HuffmanNode(left.frequency + right.frequency, '-'); parent.left = left; parent.right = right; priorityQueue.offer(parent); } return priorityQueue.poll(); } private static Map<Character, String> buildHuffmanCodes(HuffmanNode root) { Map<Character, String> huffmanCodes = new HashMap<>(); buildHuffmanCodesHelper(root, "", huffmanCodes); return huffmanCodes; } private static void buildHuffmanCodesHelper(HuffmanNode node, String code, Map<Character, String> huffmanCodes) { if (node.isLeaf()) { huffmanCodes.put(node.data, code); return; } buildHuffmanCodesHelper(node.left, code + "0", huffmanCodes); buildHuffmanCodesHelper(node.right, code + "1", huffmanCodes); } private static String encode(String text, Map<Character, String> huffmanCodes) { StringBuilder encodedText = new StringBuilder(); for (char c : text.toCharArray()) { encodedText.append(huffmanCodes.get(c)); } return encodedText.toString(); } private static String decode(String encodedText, HuffmanNode root) { StringBuilder decodedText = new StringBuilder(); HuffmanNode current = root; for (char c : encodedText.toCharArray()) { 后面代码请补充完整
最新发布
07-08

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值