Huffman编码

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值