Huffman编码

来源:互联网 发布:手机号定位软件免费 编辑:程序博客网 时间:2024/05/29 10:58
package com.supermars.practice;

import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Huffman编码 {
/*
 * no
 */
    static Scanner cin = new Scanner(new BufferedInputStream(System.in));
    static Node[] node = new Node[1 << 5];
    static Node[] Q = new Node[1 << 5];

    public static void main(String[] agrs) {
        while (cin.hasNext()) {
            int n = cin.nextInt();
            for (int i = 0; i < n; i++) {
                Node node_ = new Node();
                node_.ch = cin.next().charAt(0);
                node_.w = cin.nextInt();
                node[i] = node_;
            }
            Arrays.sort(node, 0, n, new cmph());

            int i = 0;
            int front = 1;
            Node root = new Node();
            while (true) {
                if (i >=n-1)
                    break;
                int w = node[i].w + node[i + 1].w;
                Node node_i = node[i + 1];

                if (Q[front - 1] != null && (node[i].w + Q[front - 1].w) < w) { // 选Q
                    w = node[i].w + Q[front - 1].w;
                    node_i = Q[front - 1];
                    front++;
                }
                Node node_n = new Node();
                node_n.w = w;
                if (node[i].w == node[i + 1].w)// 若两个字符权值相同,则ASCII码值小的字符为左孩子,大的为右孩子;
                {
                    if (node[i].ch < node_i.ch) {
                        node_n.l = node[i];
                        node_n.r = node_i;
                    }
                } else {
                    node_n.l = node_i;
                    node_n.r = node[i];
                }

                node_n.ch = node_n.l.ch;// 创建的新节点所代表的字符与它的左孩子的字符相同;
                root = node_n;

                Q[front - 1] = node_n;
                i++;
            }
            System.out.println(root.w);
            print_tree(root,"");

        }
    }

    private static void print_tree(Node root, String s) {

        if (root.l == null && root.r == null) {
            System.out.println(s + " " + root.ch);
            return;
        }
        if (root.r == null) {
            print_tree(root.l, s + "1");
        }
        if (root.l == null) {

            print_tree(root.l, s + "0");
        }

    }
}

class Node {
    char ch;
    int w;
    Node l, r;
}

class cmph implements Comparator<Node> {

    @Override
    public int compare(Node a, Node b) {

        return a.w - b.w;
    }

}

0 0
原创粉丝点击