切金条_哈夫曼编码

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

/**
 * 一块金条切成两半,是需要花费和长度数值一样的铜板的。
 * 比如长度为20的 金条,不管切成长度多大的两半,都要花费20个铜板。
 * 一群人想整分整块金 条,怎么分最省铜板?
 * 
 * 例如,给定数组{10,20,30},代表一共三个人,
 * 整块金条长度为10+20+30=60. 金条要分成10,20,30三个部分。 
 * 如果,先把长度60的金条分成10和50,花费60 再把长度50的金条分成20和30,花费50,一共花费110铜板。
 * 但是如果, 先把长度60的金条分成30和30,花费60 再把长度30金条分成10和20,花费30,一共花费90铜板。
 * 
 * 输入一个数组返回分割的最小值。
 * @author 小纸人
 *
 */
public class CutGold {

	//List 集合做法
//	static class MyComparator implements Comparator<Integer>{
//		public int compare(Integer o1, Integer o2) {
//			return o1 - o2;
//		}
//	}
//	public static int cut(int[] arr) {
//		int cost  = 0;
//		List<Integer> goldList = new ArrayList<Integer>();
//		for (int i = 0; i < arr.length; i++) {
//			goldList.add(arr[i]);
//		}
//		goldList.sort(new MyComparator());
//		while(goldList.size() > 1) {
//			cost += (goldList.get(0) + goldList.get(1));
//			goldList.add(goldList.get(0) + goldList.get(1));
//			goldList.remove(0);
//			goldList.remove(0);
//			goldList.sort(new MyComparator());
//		}
//		return cost;
//	}
	
	//优先队列做法
	public static int cut(int[] arr) {
		int res = 0;
		PriorityQueue<Integer> queue = new PriorityQueue<>();
		for (int i = 0; i < arr.length; i++) {
			queue.add(arr[i]);
		}
		while(queue.size() > 1) {
			int temp = queue.poll() + queue.poll(); 
			res += temp;
			queue.add(temp);
		}
		return res;
	}
	public static void main(String[] args) {
		int[] gold = {10, 20, 30};
		System.out.println(cut(gold));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
哈夫曼编码是一种压缩算法,可以将一个长的消息或文件压缩成较短的二进制码。哈夫曼编码通过构建一棵二叉树来生成编码,每个字符对应树上的一个叶子节点,该字符的编码是从根节点到叶子节点的路径上的0和1序列。 哈夫曼编码译码器的实现需要以下步骤: 1. 解析压缩文件中的哈夫曼编码表,生成哈夫曼树。 2. 读取压缩文件,并将二进制码转换为字符。 3. 使用哈夫曼树解码字符并输出原始消息或文件。 以下是一个Java实现的哈夫曼编码译码器的代码示例: ```java import java.io.*; import java.util.*; public class HuffmanDecoder { private Map<String, String> huffmanTable; public void decodeFile(String compressedFile, String outputFile) throws IOException { // 读取压缩文件 byte[] compressedBytes = readCompressedFile(compressedFile); // 解析哈夫曼编码表 huffmanTable = parseHuffmanTable(compressedBytes); // 构建哈夫曼树 Node rootNode = buildHuffmanTree(huffmanTable); // 解码文件 decodeBytes(compressedBytes, rootNode, outputFile); } private byte[] readCompressedFile(String compressedFile) throws IOException { FileInputStream inputStream = new FileInputStream(compressedFile); byte[] bytes = new byte[(int) new File(compressedFile).length()]; inputStream.read(bytes); inputStream.close(); return bytes; } private Map<String, String> parseHuffmanTable(byte[] compressedBytes) { Map<String, String> huffmanTable = new HashMap<String, String>(); String tableString = new String(compressedBytes).split("\\|")[0]; String[] entries = tableString.split(";"); for (String entry : entries) { String[] parts = entry.split(":"); huffmanTable.put(parts[0], parts[1]); } return huffmanTable; } private Node buildHuffmanTree(Map<String, String> huffmanTable) { List<Node> nodeList = new ArrayList<Node>(); for (Map.Entry<String, String> entry : huffmanTable.entrySet()) { Node node = new Node(entry.getKey(), Integer.parseInt(entry.getValue())); nodeList.add(node); } while (nodeList.size() > 1) { Collections.sort(nodeList); Node leftChild = nodeList.remove(0); Node rightChild = nodeList.remove(0); Node parent = new Node(null, leftChild.frequency + rightChild.frequency); parent.leftChild = leftChild; parent.rightChild = rightChild; nodeList.add(parent); } return nodeList.get(0); } private void decodeBytes(byte[] compressedBytes, Node rootNode, String outputFile) throws IOException { StringBuilder binaryStringBuilder = new StringBuilder(); for (int i = compressedBytes.length - 1; i >= 0; i--) { byte currentByte = compressedBytes[i]; String binaryString = Integer.toBinaryString(currentByte & 255 | 256).substring(1); binaryStringBuilder.append(binaryString); } String binaryString = binaryStringBuilder.reverse().toString(); FileOutputStream outputStream = new FileOutputStream(outputFile); Node currentNode = rootNode; for (int i = 0; i < binaryString.length(); i++) { if (binaryString.charAt(i) == '0') { currentNode = currentNode.leftChild; } else { currentNode = currentNode.rightChild; } if (currentNode.isLeaf()) { outputStream.write(currentNode.value.charAt(0)); currentNode = rootNode; } } outputStream.close(); } private class Node implements Comparable<Node> { private String value; private int frequency; private Node leftChild; private Node rightChild; public Node(String value, int frequency) { this.value = value; this.frequency = frequency; } public boolean isLeaf() { return leftChild == null && rightChild == null; } public int compareTo(Node other) { return frequency - other.frequency; } } public static void main(String[] args) throws IOException { HuffmanDecoder decoder = new HuffmanDecoder(); decoder.decodeFile("compressed_file.bin", "output_file.txt"); } } ``` 此代码解析压缩文件并生成哈夫曼树,然后使用该树来解码文件。要使用此代码,请将 `compressed_file.bin` 替换为要解码的文件名,将 `output_file.txt` 替换为输出文件名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值