|
| 1 | + |
| 2 | +/** |
| 3 | +* |
| 4 | +* @author pulkit4tech |
| 5 | +*/ |
| 6 | +import java.io.BufferedReader; |
| 7 | +import java.io.InputStreamReader; |
| 8 | +import java.io.PrintWriter; |
| 9 | +import java.util.Comparator; |
| 10 | +import java.util.PriorityQueue; |
| 11 | + |
| 12 | +// Huffman Coding for lossless data compression |
| 13 | +// Greedy Algorithm |
| 14 | +class Huffman_Coding implements Runnable { |
| 15 | + |
| 16 | + BufferedReader c; |
| 17 | + PrintWriter pout; |
| 18 | + // static long mod = 1000000007; |
| 19 | + |
| 20 | + public void run() { |
| 21 | + try { |
| 22 | + c = new BufferedReader(new InputStreamReader(System.in)); |
| 23 | + pout = new PrintWriter(System.out, true); |
| 24 | + solve(); |
| 25 | + pout.close(); |
| 26 | + } catch (Exception e) { |
| 27 | + pout.close(); |
| 28 | + e.printStackTrace(); |
| 29 | + System.exit(1); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + public static void main(String[] args) throws Exception { |
| 34 | + new Thread(new Huffman_Coding()).start(); |
| 35 | + } |
| 36 | + |
| 37 | + void solve() throws Exception { |
| 38 | + Huffman(); |
| 39 | + } |
| 40 | + |
| 41 | + void Huffman() { |
| 42 | + char arr[] = { 'p', 'u', 'l', 'k', 'i', 't' }; |
| 43 | + long freq[] = { 1, 1, 12, 13, 16, 45 }; |
| 44 | + int size = arr.length; |
| 45 | + HuffmanCodes(arr, freq, size); |
| 46 | + } |
| 47 | + |
| 48 | + class MinHeapNode { |
| 49 | + char data; |
| 50 | + long freq; |
| 51 | + MinHeapNode left, right; |
| 52 | + |
| 53 | + public MinHeapNode(char data, long freq) { |
| 54 | + this.data = data; |
| 55 | + this.freq = freq; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + void HuffmanCodes(char data[], long freq[], int size) { |
| 60 | + MinHeapNode left, right, top; |
| 61 | + |
| 62 | + PriorityQueue<MinHeapNode> pq = new PriorityQueue<>(new Comparator<MinHeapNode>() { |
| 63 | + |
| 64 | + @Override |
| 65 | + public int compare(MinHeapNode o1, MinHeapNode o2) { |
| 66 | + // TODO Auto-generated method stub |
| 67 | + return Long.compare(o1.freq, o2.freq); |
| 68 | + } |
| 69 | + }); |
| 70 | + |
| 71 | + for (int i = 0; i < size; i++) { |
| 72 | + pq.add(new MinHeapNode(data[i], freq[i])); |
| 73 | + } |
| 74 | + |
| 75 | + while (pq.size() != 1) { |
| 76 | + left = pq.poll(); |
| 77 | + right = pq.poll(); |
| 78 | + |
| 79 | + top = new MinHeapNode('$', left.freq + right.freq); |
| 80 | + top.left = left; |
| 81 | + top.right = right; |
| 82 | + |
| 83 | + pq.add(top); |
| 84 | + } |
| 85 | + |
| 86 | + printCodes(pq.peek(), ""); |
| 87 | + } |
| 88 | + |
| 89 | + void printCodes(MinHeapNode root, String str) { |
| 90 | + if (root == null) |
| 91 | + return; |
| 92 | + |
| 93 | + if (root.data != '$') |
| 94 | + pout.println(root.data + ":" + str); |
| 95 | + |
| 96 | + printCodes(root.left, str + "0"); |
| 97 | + printCodes(root.right, str + "1"); |
| 98 | + } |
| 99 | + |
| 100 | +} |
0 commit comments