【c++、数据结构课设】哈夫曼树

news2024/9/29 19:27:56

时间过的真快,转眼之间一个学期即将结束,想必这个时候大家都在准备各科的课设作业,本期内容是我的数据结构课设,希望能给大家带来帮助,如果有任何不足或需要改进的地方,欢迎各位提出宝贵的意见。

屏幕录制2023-12-24 13.43.01

课设要求

哈夫曼树应用 题目描述及功能要求

  1. 从文件 Text.txt 中读取一大段文字(字符),统计其中不同字符出现频度(百分比),将这些字符 以及对应频度统计结果存于文件 Freq.txt 中。从 Freq.txt 文件中读取频度并按此频度创建哈夫曼树。
  2. 建立哈夫曼树并将它存于文件HuffTree.txt中(以顺序存储方式,结点结构(权值,双亲,左,右). 将已在内存中的哈夫曼树以直观的方式(比如树)显示在终端上;(可以以树的凹入表示法在屏幕上显示 哈夫曼树)。
  3. 利用已经建好的哈夫曼树(如不在内存,则从文件 HuffTree.txt 中读入),给各字符进行哈夫曼编 码,并将编码结果存于另一个文件 HuffCode.txt 中。
  4. 输出该哈夫曼树的 WPL 值。
  5. 从键盘另外输入一段字符,所出现的字符,将输入的正文内容进行哈夫曼编码,如果某字符并没 有在哈夫曼编码表中,则该字符原样不变,若存在则进行二进制编码替换,将所得编码结果也保存在文 件 HuffEncoding.txt 中,同时也显示在终端上。
  6. 将二进制编码的结果从文件 HuffEncoding.txt 中读出再进行解码,显示出第 5 步中输入的那段字 符。

过程

1.数据结构

因为每个字符只能是哈夫曼树的叶子结点,所以要标记一下叶子结点。


typedef struct node {
    //权重
    int weight;
    //左右孩子,双亲
    node *lchild, *rchild, *parent;
    //叶子结点标志 false 叶子结点 true 非叶子结点
    bool flag;
} HuffmanNode;


typedef struct tree {
    //根结点
    HuffmanNode *head;
    //叶子结点个数
    int count;
} HuffmanTree;

//叶子结点数组
HuffmanNode *CH[26];

//哈夫曼编码结果
int HuffmanCode[26];

//WPL
int W;

//每个字符的权重
int weight[26];

//权重总和
int total;

//标记元素是否已经在哈夫曼树上
int status[26];


//每个字符的哈夫曼编码
int HuffmanCodes[26][26];

//
HuffmanTree *tree = new HuffmanTree;

2.主要函数

菜单


void menu() {

    cout << "-----------------------------------------------------------------------" << endl;
    cout << "|                                                                      |" << endl;
    cout << "|                            欢 迎 回 来                                 |" << endl;
    cout << "|                                                                      |" << endl;
    cout << "-----------------------------------------------------------------------" << endl;
    cout << endl;

    while (true) {
        int op;
        cout << "* 1.哈夫曼树的应用" << endl << "* 2.退出" << endl;
        cin >> op;
        if (op == 1) Huffmantree();
        else if (op == 2)bye();
        else cout << "输出有误!!!" << endl;
    }
}

退出函数

void bye() {
    ::exit(0);
}

接下来就是核心部分了

欢迎界面

void welcome() {
    cout << "-----------------------------------------------------------------------" << endl;
    cout << "|                                                                      |" << endl;
    cout << "|                        哈 夫 曼 树 应 用                               |" << endl;
    cout << "|                                                                      |" << endl;
    cout << "-----------------------------------------------------------------------" << endl;
    cout << endl;
};

初始化

void init(int flag){

    tree->count = 0;
    total = 0;
    W=0;
    if (flag)generateWeight(tree, flag);
    memset(status, 0, sizeof status);
    memset(HuffmanCodes, -1, sizeof HuffmanCodes);

}

哈夫曼树主函数


void Huffmantree() {
    //初始化

   init(0);

    //欢迎界面
    welcome();
    //生成权重
    generateWeight(tree, 0);

    //打印权重
    printWeight();
    sleep(1);

    //生成哈夫曼树
    generate(tree);

    //哈夫曼树写入文件
    writeTree(tree->head);

    //打印哈夫曼树
    printTree(0, tree->head);

    sleep(1);

    //哈夫曼编码
    code(tree, 0);


    //重新获取权重
    generateWeight(tree, 0);
    //计算WPL
    show();
    WPL(tree->head, 0);
    cout << " = " << W << endl;

    //从键盘读入字符,生成哈夫曼树
    //初始化
   init(1);
    //生成哈夫曼树
    generate(tree);

    //哈夫曼编码
    code(tree, 1);

    //输入文本
    Input();



    //解码
    decode(tree->head);
    sleep(1);
    cout<<endl;

}



生成权重

因为字符可以从文件读取,也可以从键盘读取,所以提供了两种选择,flag=0是从文件读,flag=1是从键盘读

(从文件读数据)
在这里插入图片描述


void generateWeight(HuffmanTree *t, int flag) {
    if (!flag) {
        cout << "正在努力读取文件..." << endl;
        sleep(1);
        fstream in;
        in.open("/Users/yuwei/Desktop/c++/practice/Text.txt", ios::in);
        memset(weight, 0, sizeof weight);

        char c;
        while (c = in.get()) {
            //weight=0,说明改字符第一次出现,
            if (weight[c - 'a'] == 0)t->count++;
            weight[c - 'a']++;

            //字符总数
            total++;
        }
        in.close();
    } else {
        cout << "请输入字符" << endl;
        memset(weight, 0, sizeof weight);

        string ch;
        cin >> ch;
        for (char c: ch) {
            if (c) {
                //weight=0,说明改字符第一次出现,
                if (weight[c - 'a'] == 0)t->count++;

                weight[c - 'a']++;

                //字符总数
                total++;
            }

        }

    }


}

打印权重

在这里插入图片描述


void printWeight() {

    //将权重存入文件中
    fstream out;
    out.open("/Users/yuwei/Desktop/c++/practice/Freq.txt", ios::out);

    cout << "-----------------------------------------------------------------------" << endl;
    cout << "                         权   重                                        " << endl;
    cout << "-----------------------------------------------------------------------" << endl;

    //第一行:字符
    for (int i = 0; i < 26; i++) {
        if (weight[i] != 0) {
            //在终端显示
            printf("%c\t", 'a' + i);
            // 写入文件
            out.put('a' + i);
            out.put('\t');
        }
    }

    cout << endl;
    out.put('\n');
    //第二行:权重
    for (int i = 0; i < 26; i++) {
        if (weight[i] != 0) {
            cout << weight[i] << "\t";
            //权重可能大于10,不能当作一个字符,必须转成字符串
            string s = to_string(weight[i]);
            for (char c: s) {
                out.put(c);
            }
            out.put('\t');
        }

    }
    cout << endl;
    out.put('\n');
    //第三行:比例
    for (int i = 0; i < 26; i++) {
        if (weight[i] != 0) {
            cout << (weight[i] * 100) / total << "%\t";
            string s = to_string((weight[i] * 100) / total);
            for (char c: s) {
                out.put(c);
            }
            out.put('%');
            out.put('\t');
        }
    }

    cout << endl << endl;
    out.close();

}

生成哈夫曼树


void generate(HuffmanTree *t) {
    cout << "努力构建哈夫曼树ing...";
    cout << endl;
    //间隔1s
    sleep(1);

    cout << "-----------------------------------------------------------------------" << endl;
    cout << "                         哈 夫 曼 树                                     " << endl;
    cout << "-----------------------------------------------------------------------" << endl;

    for (int i = 0; i < 26; i++) {
        //生成叶子结点
        CH[i] = new HuffmanNode;
        CH[i]->weight = 'a' + i;
        CH[i]->flag = false;

        CH[i]->lchild = CH[i]->rchild = nullptr;
        //如果weight为0说明改字符未出过,所以赋值为0x3ffff,作为标记
        if (!weight[i])weight[i] = 0x3ffff;
    }
    //f:未选结点中最小的权值最小的结点id,s:未选结点中最小的权值第二小的结点id
    int f, s;
    //进行t-》count-1次就能构造一颗哈夫曼树,比如只有两个字符,只须一步就能构造哈夫曼树
    for (int i = 1; i < t->count; i++) {

        //find :查找未选结点中最小的权值最小的结点id
        f = find();
        //加入哈夫曼树,更新status
        status[f] = 1;
        s = find();
        //用第weight[s]来储存新生成的结点
        weight[s] = weight[f] + weight[s];
        HuffmanNode *tem = new HuffmanNode;
        //更新根结点
        t->head = tem;
        //更新左右孩子
        tem->lchild = CH[f];
        tem->rchild = CH[s];
        //更新双亲
        CH[f]->parent = CH[s]->parent = tem;
        tem->weight = weight[s];
        //非叶子结点
        tem->flag = true;
        //将新结点加入CH中
        CH[s] = tem;
    }

}

find()

查找未选结点中最小的权值最小的结点id


int find() {
    int min = -1;
    //找到第一个未加入哈夫曼树结点的id
    while (status[++min]);
    for (int i = 0; i < 26; i++) {
        if (!status[i]) {
            if (weight[i] < weight[min])min = i;
        }
    }
    return min;
}

哈夫曼树写入文件

n代表null
请添加图片描述
如果是叶子结点,则会在后面加上对应的字符



void writeTree(HuffmanNode *n) {

    if (n == nullptr) return;
    fstream out;
    out.open("/Users/yuwei/Desktop/c++/practice/HuffTree.txt", ios::app);


    out.write("parent: ", 8);
    //权重可能大于10,不能当作一个字符,必须转成字符串
    if (n->parent) {
        string s = to_string(n->parent->weight);
        for (char c: s) {
            out.put(c);
        }
        out.put('\t');
    } else {
        out.write("n", 1);
        out.put('\t');
    }

    out.write("weight: ", 8);
    //非叶子结点
    if (n->flag) {

        string s = to_string(n->weight);
        for (char c: s) {
            out.put(c);
        }
        out.put('\t');
    } else {
        string s = to_string(weight[n->weight - 'a']);
        for (char c: s) {
            out.put(c);
        }
        out.put('\t');
    }

    //左右孩子

    out.write("lchild: ", 8);
    //非叶子结点

    if (n->lchild) {

        //左孩子非叶子结点
        if (n->lchild->flag) {
            string s = to_string(n->lchild->weight);
            for (char c: s) {
                out.put(c);
            }
            out.put('\t');
        } else {
            string s = to_string(weight[n->lchild->weight - 'a']);
            for (char c: s) {
                out.put(c);
            }
            out.put('\t');
        }
    } else {
        out.write("n", 1);
        out.put('\t');
    }

    //右孩子
    out.write("rchild: ", 4);
    //非叶子结点

    if (n->rchild) {

        //左孩子非叶子结点
        if (n->rchild->flag) {
            string s = to_string(n->rchild->weight);
            for (char c: s) {
                out.put(c);
            }
            out.put('\t');
        } else {
            string s = to_string(weight[n->rchild->weight - 'a']);
            for (char c: s) {
                out.put(c);
            }
            out.put('\t');
        }
    } else {
        out.write("n", 1);
        out.put('\t');
    }



    if (!n->flag) {
        //如果是叶子结点
        out.write("char: ", 6);
        out.put(n->weight);
    }
    out.put('\n');
    out.close();

    writeTree(n->lchild);
    writeTree(n->rchild);


}

打印哈夫曼树

采用以树的凹入表示法在屏幕上显示 哈夫曼树
请添加图片描述


void printTree(int num, HuffmanNode *head) {

    if (head == nullptr)return;
    //按照中序顺序便利
    printTree(num + 1, head->lchild);
    //树的凹入表示法在屏幕上显示 哈夫曼树
    for (int i = 0; i < 15 - 3 * num; i++)cout << "  ";
    if (head->flag)cout << head->weight;
    else printf("%c", head->weight);
    for (int i = 0; i <= 3 * num; i++) {
        cout << "--";
    }
    cout << endl;
    printTree(num + 1, head->rchild);

}

哈夫曼编码

请添加图片描述


void code(HuffmanTree *t, int flag) {
    cout << "哈夫曼树编码中ing...";
    cout << endl;
    sleep(1);
    if (!flag)
        //将结果写进文件
        write(0, 0, t->head);
    else
        print(0, 0, t->head);
    cout << "-----------------------------------------------------------------------" << endl;
    cout << "                         编 码 完 成                                    " << endl;
    cout << "-----------------------------------------------------------------------" << endl;
}


void write(int i, int v, HuffmanNode *t) {
    if (t == nullptr)return;

    HuffmanCode[i] = v;

    write(i + 1, 0, t->lchild);
    //如果是叶子结点则写入文件中
    if (!t->flag) {
        fstream out;
        out.open("/Users/yuwei/Desktop/c++/practice/HuffCode.txt", ios::app);
        out.put(t->weight);
        out.put(':');
        for (int j = 1; j <= i; j++)
            //数字转字符
            out.put(HuffmanCode[j] + '0');
        out.put('\n');
        out.close();

    }
    write(i + 1, 1, t->rchild);
}


计算WPL



void WPL(HuffmanNode *n, int i) {
    if (n == nullptr)return;

    WPL(n->lchild, i + 1);

    if (!n->flag) {
        W += i * weight[n->weight - 'a'];
        cout << i << " * " << weight[n->weight - 'a'] << " + ";
    }
    WPL(n->rchild, i + 1);

}

从键盘读入字符构造哈夫曼编码

在这里插入图片描述


    //哈夫曼编码
    code(tree, 1);

输入文本进行编码

在这里插入图片描述


void Input() {

    cout << "请输入文本" << endl;
    string ch;
    cin >> ch;
    fstream out;
    out.open("/Users/yuwei/Desktop/c++/practice/HuffEncoding.txt", ios::out);

    for (char c: ch) {

        if (c) {

            //不等于-1说明该字符的编码存在
            if (HuffmanCodes[c - 'a'][0] != -1) {
                for (int j = 0; HuffmanCodes[c - 'a'][j] != -1; j++) {
                    out.put(HuffmanCodes[c - 'a'][j] + '0');
                    cout << HuffmanCodes[c - 'a'][j];
                }
            } else {
                cout << c;
                out.put(c);
            }
        }
    }
    out.close();

    cout << "编码完成!!!";
    cout << endl;
    sleep(1);

}

解码

在这里插入图片描述


void decode(HuffmanNode *head) {
    cout << "努力解码中ing" << endl;
    sleep(1);
    fstream in;
    in.open("/Users/yuwei/Desktop/c++/practice/HuffEncoding.txt", ios::in);
    char c;
    HuffmanNode *tem = new HuffmanNode ;
   tem = head;
   c=in.get();
    while ((c>'a'&&c<'z')||c=='0'||c=='1'){

        if (c == '0') {
           if(tem){
               tem = tem->lchild;
               findChar(&tem);
           }

        } else if (c == '1') {
         if(tem){
             tem = tem->rchild;
             findChar(&tem);
         }

        } else cout << c;
        c=in.get();
    }
in.close();

}


void findChar(HuffmanNode **n) {

    if ((*n)->flag)return;
        //叶子结点直接输出结果
    else {
        printf("%c", (*n)->weight);
        //找到字符后,再从头开始
        (*n) = tree->head;
    }
}

完整代码

#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <fstream>
#include <string>

using namespace std;

typedef struct node {
    //权重
    int weight;
    //左右孩子,双亲
    node *lchild, *rchild, *parent;
    //叶子结点标志 false 叶子结点 true 非叶子结点
    bool flag;
} HuffmanNode;


typedef struct tree {
    //根结点
    HuffmanNode *head;
    //叶子结点个数
    int count;
} HuffmanTree;

//叶子结点数组
HuffmanNode *CH[26];

//哈夫曼编码结果
int HuffmanCode[26];

//WPL
int W;

//每个字符的权重
int weight[26];

//权重总和
int total;

//标记元素是否已经在哈夫曼树上
int status[26];


//每个字符的哈夫曼编码
int HuffmanCodes[26][26];

//
HuffmanTree *tree = new HuffmanTree;

// 欢迎界面
void welcome();

//生成权重,flag:0:从文件读取字符,1:从键盘读入
void generateWeight(HuffmanTree *t, int flag);

//打印哈夫曼树, num是层数
void printTree(int num, HuffmanNode *head);

//将哈夫曼树写入文件
void writeTree(HuffmanNode *n);

//计算WPL显示界面
void show();


void WPL(node *head, int i);

//哈夫曼树核心函数
void Huffmantree();


void bye();

//flag:0 编码结果写入文件,flag:1编码结果存入数组
void code(HuffmanTree *t, int flag);

//打印权重
void printWeight();

//查找未选结点中最小的权值最小的结点id
int find();

//将编码结果写入文件 , num :层数 v:编码值
void write(int num, int v, HuffmanNode *n);

//将编码结果写入二维数组 , num :层数 v:编码值
void print(int i, int v, HuffmanNode *t);

//从键盘输入内容,并将结果存入文件中
void Input();

//生成哈夫曼树
void generate(HuffmanTree *t);

//解码
void decode(HuffmanNode *head);

//根据哈夫曼编码找字符
void findChar(HuffmanNode **n);
//初始化
void init(int flag);
void menu() {

    cout << "-----------------------------------------------------------------------" << endl;
    cout << "|                                                                      |" << endl;
    cout << "|                            欢 迎 回 来                                 |" << endl;
    cout << "|                                                                      |" << endl;
    cout << "-----------------------------------------------------------------------" << endl;
    cout << endl;

    while (true) {
        int op;
        cout << "* 1.哈夫曼树的应用" << endl << "* 2.退出" << endl;
        cin >> op;
        if (op == 1) Huffmantree();
        else if (op == 2)bye();
        else cout << "输出有误!!!" << endl;
    }
}

void welcome() {
    cout << "-----------------------------------------------------------------------" << endl;
    cout << "|                                                                      |" << endl;
    cout << "|                        哈 夫 曼 树 应 用                               |" << endl;
    cout << "|                                                                      |" << endl;
    cout << "-----------------------------------------------------------------------" << endl;
    cout << endl;
};
void init(int flag){

    tree->count = 0;
    total = 0;
    W=0;
    if (flag)generateWeight(tree, flag);
    memset(status, 0, sizeof status);
    memset(HuffmanCodes, -1, sizeof HuffmanCodes);

}

void Huffmantree() {
    //初始化

   init(0);

    //欢迎界面
    welcome();
    //生成权重
    generateWeight(tree, 0);

    //打印权重
    printWeight();
    sleep(1);

    //生成哈夫曼树
    generate(tree);

    //哈夫曼树写入文件
    writeTree(tree->head);

    //打印哈夫曼树
    printTree(0, tree->head);

    sleep(1);

    //哈夫曼编码
    code(tree, 0);


    //重新获取权重
    generateWeight(tree, 0);
    //计算WPL
    show();
    WPL(tree->head, 0);
    cout << " = " << W << endl;

    //从键盘读入字符,生成哈夫曼树
    //初始化
   init(1);
    //生成哈夫曼树
    generate(tree);

    //哈夫曼编码
    code(tree, 1);

    //输入文本
    Input();



    //解码
    decode(tree->head);
    sleep(1);
    cout<<endl;

}


void bye() {
    ::exit(0);
}

void printWeight() {

    //将权重存入文件中
    fstream out;
    out.open("/Users/yuwei/Desktop/c++/practice/Freq.txt", ios::out);

    cout << "-----------------------------------------------------------------------" << endl;
    cout << "                         权   重                                        " << endl;
    cout << "-----------------------------------------------------------------------" << endl;

    //第一行:字符
    for (int i = 0; i < 26; i++) {
        if (weight[i] != 0) {
            //在终端显示
            printf("%c\t", 'a' + i);
            // 写入文件
            out.put('a' + i);
            out.put('\t');
        }
    }

    cout << endl;
    out.put('\n');
    //第二行:权重
    for (int i = 0; i < 26; i++) {
        if (weight[i] != 0) {
            cout << weight[i] << "\t";
            //权重可能大于10,不能当作一个字符,必须转成字符串
            string s = to_string(weight[i]);
            for (char c: s) {
                out.put(c);
            }
            out.put('\t');
        }

    }
    cout << endl;
    out.put('\n');
    //第三行:比例
    for (int i = 0; i < 26; i++) {
        if (weight[i] != 0) {
            cout << (weight[i] * 100) / total << "%\t";
            string s = to_string((weight[i] * 100) / total);
            for (char c: s) {
                out.put(c);
            }
            out.put('%');
            out.put('\t');
        }
    }

    cout << endl << endl;
    out.close();

}

void generate(HuffmanTree *t) {
    cout << "努力构建哈夫曼树ing...";
    cout << endl;
    //间隔1s
    sleep(1);

    cout << "-----------------------------------------------------------------------" << endl;
    cout << "                         哈 夫 曼 树                                     " << endl;
    cout << "-----------------------------------------------------------------------" << endl;

    for (int i = 0; i < 26; i++) {
        //生成叶子结点
        CH[i] = new HuffmanNode;
        CH[i]->weight = 'a' + i;
        CH[i]->flag = false;

        CH[i]->lchild = CH[i]->rchild = nullptr;
        //如果weight为0说明改字符未出过,所以赋值为0x3ffff,作为标记
        if (!weight[i])weight[i] = 0x3ffff;
    }
    //f:未选结点中最小的权值最小的结点id,s:未选结点中最小的权值第二小的结点id
    int f, s;
    //进行t-》count-1次就能构造一颗哈夫曼树,比如只有两个字符,只须一步就能构造哈夫曼树
    for (int i = 1; i < t->count; i++) {

        //find :查找未选结点中最小的权值最小的结点id
        f = find();
        //加入哈夫曼树,更新status
        status[f] = 1;
        s = find();
        //用第weight[s]来储存新生成的结点
        weight[s] = weight[f] + weight[s];
        HuffmanNode *tem = new HuffmanNode;
        //更新根结点
        t->head = tem;
        //更新左右孩子
        tem->lchild = CH[f];
        tem->rchild = CH[s];
        //更新双亲
        CH[f]->parent = CH[s]->parent = tem;
        tem->weight = weight[s];
        //非叶子结点
        tem->flag = true;
        //将新结点加入CH中
        CH[s] = tem;
    }

}

void printTree(int num, HuffmanNode *head) {

    if (head == nullptr)return;
    //按照中序顺序便利
    printTree(num + 1, head->lchild);
    //树的凹入表示法在屏幕上显示 哈夫曼树
    for (int i = 0; i < 15 - 3 * num; i++)cout << "  ";
    if (head->flag)cout << head->weight;
    else printf("%c", head->weight);
    for (int i = 0; i <= 3 * num; i++) {
        cout << "--";
    }
    cout << endl;
    printTree(num + 1, head->rchild);

}

int find() {
    int min = -1;
    //找到第一个未加入哈夫曼树结点的id
    while (status[++min]);
    for (int i = 0; i < 26; i++) {
        if (!status[i]) {
            if (weight[i] < weight[min])min = i;
        }
    }
    return min;
}

void code(HuffmanTree *t, int flag) {
    cout << "哈夫曼树编码中ing...";
    cout << endl;
    sleep(1);
    if (!flag)
        //将结果写进文件
        write(0, 0, t->head);
    else
        print(0, 0, t->head);
    cout << "-----------------------------------------------------------------------" << endl;
    cout << "                         编 码 完 成                                    " << endl;
    cout << "-----------------------------------------------------------------------" << endl;
}

void write(int i, int v, HuffmanNode *t) {
    if (t == nullptr)return;

    HuffmanCode[i] = v;

    write(i + 1, 0, t->lchild);
    //如果是叶子结点则写入文件中
    if (!t->flag) {
        fstream out;
        out.open("/Users/yuwei/Desktop/c++/practice/HuffCode.txt", ios::app);
        out.put(t->weight);
        out.put(':');
        for (int j = 1; j <= i; j++)
            //数字转字符
            out.put(HuffmanCode[j] + '0');
        out.put('\n');
        out.close();

    }
    write(i + 1, 1, t->rchild);
}

void writeTree(HuffmanNode *n) {

    if (n == nullptr) return;
    fstream out;
    out.open("/Users/yuwei/Desktop/c++/practice/HuffTree.txt", ios::app);


    out.write("parent: ", 8);
    //权重可能大于10,不能当作一个字符,必须转成字符串
    if (n->parent) {
        string s = to_string(n->parent->weight);
        for (char c: s) {
            out.put(c);
        }
        out.put('\t');
    } else {
        out.write("n", 1);
        out.put('\t');
    }

    out.write("weight: ", 8);
    //非叶子结点
    if (n->flag) {

        string s = to_string(n->weight);
        for (char c: s) {
            out.put(c);
        }
        out.put('\t');
    } else {
        string s = to_string(weight[n->weight - 'a']);
        for (char c: s) {
            out.put(c);
        }
        out.put('\t');
    }

    //左右孩子

    out.write("lchild: ", 8);
    //非叶子结点

    if (n->lchild) {

        //左孩子非叶子结点
        if (n->lchild->flag) {
            string s = to_string(n->lchild->weight);
            for (char c: s) {
                out.put(c);
            }
            out.put('\t');
        } else {
            string s = to_string(weight[n->lchild->weight - 'a']);
            for (char c: s) {
                out.put(c);
            }
            out.put('\t');
        }
    } else {
        out.write("n", 1);
        out.put('\t');
    }

    //右孩子
    out.write("rchild: ", 4);
    //非叶子结点

    if (n->rchild) {

        //左孩子非叶子结点
        if (n->rchild->flag) {
            string s = to_string(n->rchild->weight);
            for (char c: s) {
                out.put(c);
            }
            out.put('\t');
        } else {
            string s = to_string(weight[n->rchild->weight - 'a']);
            for (char c: s) {
                out.put(c);
            }
            out.put('\t');
        }
    } else {
        out.write("n", 1);
        out.put('\t');
    }



    if (!n->flag) {
        //如果是叶子结点
        out.write("char: ", 6);
        out.put(n->weight);
    }
    out.put('\n');
    out.close();

    writeTree(n->lchild);
    writeTree(n->rchild);


}

//
void print(int i, int v, HuffmanNode *t) {
    if (t == nullptr)return;
    HuffmanCode[i] = v;

    print(i + 1, 0, t->lchild);
    //如果是叶子结点则写入文件中
    if (!t->flag) {
        for (int j = 1; j <= i; j++) {
            //数字转字符
            HuffmanCodes[t->weight - 'a'][j - 1] = HuffmanCode[j];
        }

    }
    print(i + 1, 1, t->rchild);

}

void Input() {

    cout << "请输入文本" << endl;
    string ch;
    cin >> ch;
    fstream out;
    out.open("/Users/yuwei/Desktop/c++/practice/HuffEncoding.txt", ios::out);

    for (char c: ch) {

        if (c) {

            //不等于-1说明该字符的编码存在1
            if (HuffmanCodes[c - 'a'][0] != -1) {
                for (int j = 0; HuffmanCodes[c - 'a'][j] != -1; j++) {
                    out.put(HuffmanCodes[c - 'a'][j] + '0');
                    cout << HuffmanCodes[c - 'a'][j];
                }
            } else {
                cout << c;
                out.put(c);
            }
        }
    }
    out.close();

    cout << "编码完成!!!";
    cout << endl;
    sleep(1);

}


void WPL(HuffmanNode *n, int i) {
    if (n == nullptr)return;

    WPL(n->lchild, i + 1);

    if (!n->flag) {
        W += i * weight[n->weight - 'a'];
        cout << i << " * " << weight[n->weight - 'a'] << " + ";
    }
    WPL(n->rchild, i + 1);

}

void show() {
    cout << "努力计算WPLing...";
    cout << endl;
    sleep(1);

    cout << "-----------------------------------------------------------------------" << endl;
    cout << "                           W  P  L                                     " << endl;
    cout << "-----------------------------------------------------------------------" << endl;

    cout << "WPL: ";
}

void generateWeight(HuffmanTree *t, int flag) {
    if (!flag) {
        cout << "正在努力读取文件..." << endl;
        sleep(1);
        fstream in;
        in.open("/Users/yuwei/Desktop/c++/practice/Text.txt", ios::in);
        memset(weight, 0, sizeof weight);

        char c;
        while (c = in.get()) {
            //weight=0,说明改字符第一次出现,
            if (weight[c - 'a'] == 0)t->count++;
            weight[c - 'a']++;

            //字符总数
            total++;
        }
        in.close();
    } else {
        cout << "请输入字符" << endl;
        memset(weight, 0, sizeof weight);

        string ch;
        cin >> ch;
        for (char c: ch) {
            if (c) {
                //weight=0,说明改字符第一次出现,
                if (weight[c - 'a'] == 0)t->count++;

                weight[c - 'a']++;

                //字符总数
                total++;
            }

        }

    }


}

void decode(HuffmanNode *head) {
    cout << "努力解码中ing" << endl;
    sleep(1);
    fstream in;
    in.open("/Users/yuwei/Desktop/c++/practice/HuffEncoding.txt", ios::in);
    char c;
    HuffmanNode *tem = new HuffmanNode ;
   tem = head;
   c=in.get();
    while ((c>'a'&&c<'z')||c=='0'||c=='1'){

        if (c == '0') {
           if(tem){
               tem = tem->lchild;
               findChar(&tem);
           }

        } else if (c == '1') {
         if(tem){
             tem = tem->rchild;
             findChar(&tem);
         }

        } else cout << c;
        c=in.get();
    }
in.close();

}

void findChar(HuffmanNode **n) {

    if ((*n)->flag)return;
        //叶子结点直接输出结果
    else {
        printf("%c", (*n)->weight);
        //找到字符后,再从头开始
        (*n) = tree->head;
    }
}

int main() {
    menu();
}

小结

本课设用到的知识
树的创建和遍历
哈夫曼树的构建和应用
c++文件的读写
在这里插入图片描述

再次感谢你的阅读,希望本文对你有所帮助。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1333485.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

2023年12月24日学习总结

今日to do list&#xff1a; 做kaggle上面的流量预测项目☠️ 学习时不刷手机&#x1f921; okkkkkkkkkkkkkk 开始&#x1f44d;&#x1f34e; 0、我在干什么&#xff1f; 我在预测一个名字叫做elborn基站的下行链路流量&#xff0c;用过去29天的数据预测未来10天的数据 1、…

Json和Xml

一、前言 学习心得&#xff1a;C# 入门经典第8版书中的第21章《Json和Xml》 二、Xml的介绍 Xml的含义&#xff1a; 可标记性语言&#xff0c;它将数据以一种特别简单文本格式储存。让所有人和几乎所有的计算机都能理解。 XML文件示例&#xff1a; <?xml version"1.…

HarmonyOS - 基础组件绘制

文章目录 所有组件开发 tipsBlankTextImageTextInputButtonLoadingProgress 本文改编自&#xff1a;<HarmonyOS第一课>从简单的页面开始 https://developer.huawei.com/consumer/cn/training/course/slightMooc/C101667360160710997 所有组件 在 macOS 上&#xff0c;组…

原来电脑并不需要重装系统才能恢复出厂设置,这个操作学起来!

前言 小伙伴们应该都知道手机上有恢复出厂设置的功能&#xff0c;如果想要把手机送给朋友或者卖给别人&#xff0c;就会先恢复出厂设置。 但换到Windows电脑上之后&#xff0c;如果出现同样的情况&#xff0c;就会第一时间想到重装系统。就好像Windows电脑上不存在恢复出厂设…

顶级旗舰ET9出道,蔚来还是那个「最不计成本」的中国车品牌

作者 |张祥威 编辑 |德新 2008年&#xff0c;李斌和新浪的曹国伟几人一起喝酒&#xff0c;发了第一条微博&#xff0c;「天冷带围巾&#xff0c;心冷发微博」&#xff0c;一晚上涨了2000多个粉丝&#xff0c;他偶尔还会针砭时事&#xff0c;很快积累了最早一波粉丝。 创立蔚来…

[Linux] Mysql数据库中的用户管理与授权

一、登录用户的管理 1.1 查看用户密码的信息 用户信息存放在 mysql 数据库下的 user 表&#xff08;MySQL 服务下存在一个系统自带的 mysql 数据库&#xff09;。 use mysql ; show tables; desc user; 查看密码信息的命令&#xff1a; 能看到密码信息&#xff1a;是经过加…

Python入门学习篇(七)——列表切片字符串切片

1 列表切片 1.1 语法结构 列表的变量名[start:end:step] """ start表示截取的开始位置(下标从0 开始)&#xff0c;不填是默认是0 end截取的最后一个元素位置1, 不填是截取到最后一个元素 step 每隔几个(step-1)去获取值,默认没填时,step值为1 因而 取值范围为…

ROS2 学习09--ros 中的通信接口的定义以及如何创建自定义msg、srv和action文件

在ROS系统中&#xff0c;无论话题还是服务&#xff0c;或者我们后续将要学习的动作&#xff0c;都会用到一个重要的概念——通信接口。 通信并不是一个人自言自语&#xff0c;而是两个甚至更多个人&#xff0c;你来我往的交流&#xff0c;交流的内容是什么呢&#xff1f;为了让…

PCIe surprise down异常与DPC功能分析-part1

在PCIe系统中&#xff0c;多个设备通过PCIe链路连接在一起&#xff0c;形成一个复杂的互连网络。这些设备可能包括CPU、GPU、网卡、存储控制器等。由于PCIe是一种高速、低延迟的总线标准&#xff0c;任何设备故障或错误都可能迅速传播到整个系统&#xff0c;导致数据损坏、系统…

基于Java (spring-boot)的仓库管理系统

一、项目介绍 本系统的使用者一共有系统管理员、仓库管理员和普通用户这3种角色: 1.系统管理员&#xff1a;通过登录系统后&#xff0c;可以进行管理员和用户信息的管理、仓库和物品分类的管理&#xff0c;以及操作日志的查询&#xff0c;具有全面的系统管理权限。 2.仓库管理…

labelme标注的json文件数据转成coco数据集格式(可处理目标框和实例分割)

这里主要是搬运一下能找到的 labelme标注的json文件数据转成coco数据集格式&#xff08;可处理目标框和实例分割&#xff09;的代码&#xff0c;以供需要时参考和提供相关帮助。 1、官方labelme实现 如下是labelme官方网址&#xff0c;提供了源代码&#xff0c;以及相关使用方…

【数据保护】数据匿名的自定义NLP方法

自我介绍 做一个简单介绍&#xff0c;酒架年近48 &#xff0c;有20多年IT工作经历&#xff0c;目前在一家500强做企业架构&#xff0e;因为工作需要&#xff0c;另外也因为兴趣涉猎比较广&#xff0c;为了自己学习建立了三个博客&#xff0c;分别是【全球IT瞭望】&#xff0c;【…

Android画布Canvas裁剪clipRect,Kotlin

Android画布Canvas裁剪clipRect&#xff0c;Kotlin private fun mydraw() {val originBmp BitmapFactory.decodeResource(resources, R.mipmap.pic).copy(Bitmap.Config.ARGB_8888, true)val newBmp Bitmap.createBitmap(originBmp.width, originBmp.height, Bitmap.Config.A…

【C++11/17】std::map高效插入

我们在使用stl的映射容器std::map时&#xff0c;经常需要向容器中插入数据。由于map的元素key值是唯一的&#xff0c;我们经常遇到这样的场景&#xff1a; 向map中插入元素时&#xff0c;指定的key已经存在则直接更新&#xff1b;指定的key不存在&#xff0c;然后才做插入操作…

四色问题(图论)python

四色问题是一种著名的图论问题&#xff0c;它要求在给定的地图上给每个区域着一种颜色&#xff0c;使得相邻的区域颜色不同&#xff0c;而只使用四种颜色。这个问题可以通过图的着色来解决&#xff0c;其中图的节点表示区域&#xff0c;边表示相邻的关系。 在 Python 中&#…

服装店管理系统打造门店拓客、促活、存留营销方案

打造门店拓客、促活和存留营销方案对于服装店的管理系统来说是非常重要的。以下是一些可行的方案&#xff1a; 1. 会员管理系统&#xff1a;引入会员管理功能&#xff0c;建立会员档案&#xff0c;跟踪会员消费记录和偏好。通过会员系统&#xff0c;可以实施积分制度、生日礼品…

Kioptrix-2

环境搭建 这个靶场环境稍微有点麻烦&#xff0c;首次打开的时候&#xff0c;需要将靶机从VM中移除&#xff08;注意是 从VM里面移除&#xff09;&#xff0c;然后利用nodpad等工具打开vmx文件&#xff0c;然后两步&#xff1a; 所有以“ethernet0”开头的条目并保存更改。然后…

DBAPI如何进行API请求参数校验

DBAPI如何进行API请求参数校验 实操 案例1- 校验参数字符串长度不能大于4 在参数校验项目点击新增参数校验规则 在校验脚本填写JavaScript脚本内容&#xff0c;就写js代码name.length < 5&#xff0c;然后失败提示信息填上相应的内容&#xff0c;当这个参数校验规则执行不…

GPT每预测一个token就要调用一次模型

问题&#xff1a;下图调用了多少次模型&#xff1f; 不久以前我以为是调用一次 通过看代码是输出多少个token就调用多少次&#xff0c;如图所示&#xff1a; 我理解为分类模型 预测下一个token可以理解为分类模型&#xff0c;类别是vocab的所有token&#xff0c;每一次调用都…

【K8S in Action】服务:让客户端发现pod 并与之通信(2)

一 通过Ingress暴露服务 Ingress (名词&#xff09; 一一进入或进入的行为&#xff1b;进入的权利&#xff1b;进入的手段或地点&#xff1b;入口。一个重要的原因是每个 LoadBalancer 服务都需要自己的负载均衡器&#xff0c; 以及 独有的公有 IP 地址&#xff0c; 而 Ingres…