当前位置:网站首页>Question d: Haffman coding
Question d: Haffman coding
2022-07-04 01:58:00 【Wait for dawn forever】
Title Description
Huffman code must be familiar to you ( It doesn't matter if I'm not familiar with it , Find out for yourself ...). Now I give you a string of characters and their corresponding weights , Let you construct Huffman tree , So as to determine the Huffman code of each character . Of course , Here are some small rules :
1. The left subtree of Huffman tree is coded as 0, The right subtree is coded as 1;
2. If the weight of two characters is the same , be ASCII Characters with small code value are left children , The big one is the right child ;
3. The characters represented by the created new node are the same as those of its child ;
4. All characters are ASCII On the code table 32-96 Characters between ( namely “ ” To “`” Characters between ).
Input
The input contains multiple sets of data ( No more than 100 Group )
The first row of each group of data is an integer n, Represents the number of characters . Next n That's ok , Each line has one character ch And an integer weight, According to the character ch The corresponding weight , Space separates the middle .
Input data to ensure that the characters of each group of test data will not be repeated .
Output
For each group of test data , Output the corresponding characters and their Huffman coding results in the input order , See the example for the specific format .
The sample input
3
a 10
b 5
c 8
4
a 1
b 1
c 1
d 1
Sample output
a:0
b:10
c:11
a:00
b:01
c:10
d:11
Ideas : Top down Huffman coding .
#include <cstdio>
#include <climits>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 110;
struct chardata {
char ch;
int weight;
} w[maxn];
struct HuffmanNode {
int weight;
int parent, lchild, rchild;
} Node[maxn * 2];
void searchMin(int &a, int &b, int n) {
int min = INT_MAX;
// Find the decimal number a
for (int i = 1; i <= n; i++) {
if (Node[i].parent == 0 && Node[i].weight < min) {
min = Node[i].weight;
a = i;
}
}
min = INT_MAX;
// Find the sequence number of the next decimal b
for (int i = 1; i <= n; i++) {
if (Node[i].parent == 0 && Node[i].weight < min && i != a) {
min = Node[i].weight;
b = i;
}
}
// Guarantee serial number a Less than serial number b
if (a > b) {
swap(a, b);
}
}
void HuffmanCode(int n, chardata *w, char **&ans) {
int m = 2 * n - 1;
// Initialize original n Leaf node
for (int i = 1; i <= n; i++) {
Node[i].parent = Node[i].lchild = Node[i].rchild = 0;
Node[i].weight = w[i].weight;
}
// structure Huffman Binary tree
for (int i = n + 1; i <= m; i++) {
int a, b;
searchMin(a, b, i - 1);
Node[i].lchild = a;
Node[i].rchild = b;
Node[i].weight = Node[a].weight + Node[b].weight;
Node[i].parent = 0;
Node[a].parent = Node[b].parent = i; // Mark parent node
}
int c, f, len;
char temp[n];
ans = new char *[n + 1];
for (int i = 1; i <= n; i++) {
c = i;
len = n;
temp[len] = 0;
// Bottom up
while (Node[c].parent != 0) {
// Up to the root node
f = Node[c].parent; // Parent node
if (Node[f].lchild == c) {
// Left 0
temp[--len] = '0';
} else {
// Right 1
temp[--len] = '1';
}
c = f; // Keep going up
}
ans[i] = new char[n - len + 1];
strcpy(ans[i], temp + len); // Copied to the ans
}
}
int main() {
int n;
char **ans;
while (scanf("%d", &n) != EOF) {
for (int i = 1; i <= n; i++) {
getchar();
scanf("%c %d", &w[i].ch, &w[i].weight);
}
HuffmanCode(n, w, ans);
for (int i = 1; i <= n; i++) {
printf("%c:%s\n", w[i].ch, ans[i]);
}
}
delete ans;
return 0;
}
边栏推荐
- Software product download collection
- File contains vulnerability summary
- Chapter 3.4: starrocks data import - Flink connector and CDC second level data synchronization
- Hunan University | robust Multi-Agent Reinforcement Learning in noisy environment
- Magical usage of edge browser (highly recommended by program ape and student party)
- How can enterprises optimize the best cost of cloud computing?
- Force buckle day32
- Lightweight Pyramid Networks for Image Deraining
- Containerization technology stack
- Valentine's Day - 9 jigsaw puzzles with deep love in wechat circle of friends
猜你喜欢
MySQL statement learning record
Jerry's watch listens to the message notification of the target third-party software and pushes the message to the device [article]
Applet graduation project is based on wechat classroom laboratory reservation applet graduation project opening report function reference
Write the first CUDA program
Final consistency of MESI cache in CPU -- why does CPU need cache
The reasons why QT fails to connect to the database and common solutions
Conditional statements of shell programming
Introduction to Tianchi news recommendation: 4 Characteristic Engineering
Maximum likelihood method, likelihood function and log likelihood function
Iclr2022 | ontoprotein: protein pre training integrated with gene ontology knowledge
随机推荐
Example 072 calculation of salary it is known that the base salary of an employee of a company is 500 yuan. The amount of software sold by the employee and the Commission method are as follows: Sales
Writeup (real questions and analysis of ciscn over the years) of the preliminary competition of national college students' information security competition
Ceramic metal crowns - current market situation and future development trend
Méthode de calcul de la connexion MSSQL de la carte esp32c3
C import Xls data method summary III (processing data in datatable)
Pesticide synergist - current market situation and future development trend
MySQL utilise la vue pour signaler les erreurs, Explicit / show ne peut pas être publié; Verrouillage des fichiers privés pour la table sous - jacente
In yolov5, denselayer is used to replace focus, and the FPN structure is changed to bi FPN
Chinese Mitten Crab - current market situation and future development trend
SRCNN:Learning a Deep Convolutional Network for Image Super-Resolution
Chain ide -- the infrastructure of the metauniverse
It's corrected. There's one missing < /script >, why doesn't the following template come out?
Huawei BFD and NQA
Applet graduation project based on wechat selection voting applet graduation project opening report function reference
MySQL - use of aggregate functions and group by groups
Notice on Soliciting Opinions on the draft of information security technology mobile Internet application (APP) life cycle security management guide
Prose article appreciation - the rain in the warm country has never changed into cold, hard and brilliant flowers. Knowledgeable people think he is monotonous, and he thinks he is unlucky, doesn't he?
How to delete MySQL components using xshell7?
Force buckle day32
Feign implements dynamic URL