哈夫曼解码

【问题描述】

给定一组字符的Huffman编码表(从标准输入读取),给定一个用该编码表进行编码的Huffman编码文件(存在当前目录下的in.txt中),编写程序对Huffman编码文件进行解码。

例如给定的一组字符的Huffman编码表为:

6

1:111

2:0

+:110

*:1010

=:1011

8:100

第一行的6表示要对6个不同的字符进行编码,后面每行中冒号(:)左边的字符为待编码的字符,右边为其Huffman编码,冒号两边无空格。对于该编码表,对应的Huffman树(树中左分支表示0,右分支表示1)应为:

假如Huffman编码文件in.txt中的内容(由0和1字符组成的序列)为:

111011010010110101010011001100

则遍历上述Huffman树即可对该文件进行解码,解码后的文件内容为:

12+8=2*8+2+2

【输入形式】

先从标准输入读入待编码的字符个数(大于等于2,小于等于30),然后分行输入各字符的Huffman编码(先输入字符,再输入其编码,字符和编码中间以一个英文字符冒号:分隔),编码只由0和1组成。

Huffman编码文件为当前目录下的in.txt文本文件,即:其中的0和1都是以单个字符的形式存储,文件末尾有一个回车换行符。

【输出形式】

将解码后的文件内容输出到标准输出上

【样例输入】

6

1:111

2:0

+:110

*:1010

=:1011

8:100

假如in.txt中的内容为:

1110110100101101010100110011001100

【样例输出】

12+8=2*8+2+2

【样例说明】

从标准输入读取了6个字符的Huffman编码,因为规定Huffman树中左分支表示0,右分支表示1,所以利用该编码表可构造上述Huffman树(见图1)。遍历该Huffman树对编码文件in.txt的进行解码,即可得到解码后的原文件内容。

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<string>
#include <stdio.h>
using namespace std;
class node
{
public:
int data;//操作数
char op;//操作符
bool flag;//true表示操作数,false表示操作符
node*lchild;
node*rchild;
node():data(0),op(0),flag(true),lchild(nullptr),rchild(nullptr){};
node(int n):data(n),op(0),flag(false),lchild(nullptr),rchild(nullptr){};
node(int n,char c):data(n),op(c),flag(true),lchild(nullptr),rchild(nullptr){}
};
class myTree
{
    public:
    node*root;
    void creatMytree(int n);
};
void removeSpace(string &str)
{
    std::string::size_type index = 0;
    if(!str.empty())
    {
        while((index=str.find(' ',index))!=string::npos)
        {
            str.erase(index,1);
        }
    }
}
void myTree::creatMytree(int n)
{
    root = new node();//创建根节点
    for(int i=0;i<n;i++)
    {
        string input;
        cin>>input;
        removeSpace(input);
        int colonPos=input.find(':');
        string path = input.substr(colonPos+1);
        node*current = root;
        for(char ch:path)
        {
            if(ch == '0')
            {
                if(!current->lchild)
                {
                    current->lchild = new node();
                }
                current = current->lchild;
            }else if(ch== '1')
            {
                if(!current->rchild)
                {
                    current->rchild = new node();
                }
                current = current->rchild;
            }
        }
        if(input[0]>='0'&&input[0]<='9')
        {
           //获取字符串中的数字
 int num=stoi(input.substr(0,colonPos));//从输入的字符串中提取第一个冒号之前的数字,并将其转化为整数类型,这在解析二叉树的时候非常实用。便于将字符串转化为数据。
 //特别是在大于一位数的转化上非常实用。
            current->data = num;
            current->flag = true;
        }
        else{
            char num = input[0];
            current->op = num;
            current->flag=false;
        }
    }
}
void decodeMyTree(node*root,string str)
{
    node*current = root;
    int num;
    while(!str.empty())
    {
        num=0;current=root;
        for(char ch:str)
        {
            if(ch=='0')
            {
                if(current->lchild!=nullptr)
                current=current->lchild;
                else break;
            }
            else if(ch=='1')
            {
                if(current->rchild!=nullptr)
                current = current->rchild;
                else break;
            }
            num++;
        }
        if(current->flag==true)
        {
            cout<<current->data;
        }
        else{
            cout<<current->op;
        }
        str.erase(0,num);

    }
}
int main(void)
{
    int n;
    cin>>n;
    myTree*t = new myTree();
    t->creatMytree(n);
    freopen("in.txt","r",stdin);
    string str;
    cin>>str;
    removeSpace(str);
    decodeMyTree(t->root,str);
    return 0;
}

【问题描述】

给定一个无向图和一个图顶点,采用邻接表存储无向图,编程输出该图深度优先遍历的顶点序列;删除给定顶点后输出广度优先遍历的顶点序列。

给定的无向图和图顶点满足以下要求:

1、无向图的顶点个数n大于等于3,小于等于100,输入时顶点编号用整数0~n-1表示;

2、无向图在删除给定顶点前后都是连通的;

3、无论何种遍历,都是从编号为0的顶点开始遍历,访问相邻顶点时按照编号从小到大的顺序访问;

4、删除的顶点编号不为0。

【输入形式】

先从标准输入中输入图的顶点个数和边的个数,两整数之间以一个空格分隔,然后从下一行开始分行输入每条边的信息(用边两端的顶点编号表示一条边,以一个空格分隔顶点编号,边的输入次序和每条边两端顶点编号的输入次序可以是任意的,但边不会重复输入),最后在新的一行上输入要删除的顶点编号。

【输出形式】

分行输出各遍历顶点序列,顶点编号之间以一个空格分隔。先输出删除给定顶点前的深度优先遍历顶点序列,再输出删除给定顶点后的广度优先遍历顶点序列。

【样例输入】

9  10

0 1

0 2

1 3

1 4

1 8

2 5

2 7

3 6

5 7

6   8

3

【样例输出】

0 1 3 6 8 4 2 5 7

0 1 2 4 8 5 7 6

【样例说明】

输入的无向图有9个顶点,10条边(如下图所示),要删除的顶点编号为3。

#include<iostream>
#include <vector>
#include<queue>
#include<list>
#include <string>
#include<algorithm>
using namespace std;
class Graph
{
    int V;//顶点个数
    list<int>*adj;//邻接表 
    public:
    Graph(int V);//构造函数
    void addEdge(int v,int w);//添加边
    void DFS(int v,vector<bool>&visited);//深度优先搜索
    void BFS(int s);//广度优先搜索
    void removeVertex(int v);//删除节点
    void printDFS(int start);//输出深度优先搜索序列
    void printBFS(int start);//输出广度优先搜索序列
};
Graph::Graph(int V)//构造函数,将实参V传递给形参V,表示有V个顶点
{
    this->V = V;
    adj = new list<int>[V];//邻接表有v个元素
}
void Graph::addEdge(int v,int w)
{
   adj[v].push_back(w);//添加w的边添加到v的邻接表中
    adj[w].push_back(v);//添加v的边到w的邻接表中
}
void Graph::DFS(int v,vector<bool>&visited)//邻接表的深度优先搜索实现
{
    visited[v]=true;//索引为v的元素设置为true,表示当前节点v已经被访问过。
    cout<<v<<" ";
    adj[v].sort();//邻接表排序
    list<int>::iterator i;
    for(i = adj[v].begin();i!=adj[v].end();i++)
    if(!visited[*i])
    DFS(*i,visited);
}
void Graph::BFS(int s)//邻接表的广度优先搜索实现
{
    vector<bool>visited(V,false);
    queue<int>queue;
    visited[s]=true;
    queue.push(s);
    while(!queue.empty())
    {
        s=queue.front();
        cout<<s<<" ";
        queue.pop();
        adj[s].sort();
        for(auto i=adj[s].begin();i!=adj[s].end();i++)
        if(!visited[*i])
        {
            visited[*i]=true;
            queue.push(*i);
        }
    }
}
void Graph::removeVertex(int v)
{
    for(int i=0;i<V;i++)
    {
        adj[i].remove(v);
    }
    adj[v].clear();
}
void Graph::printDFS(int start)
{
    vector<bool>visited(V,false);
    DFS(start,visited);
    cout<<endl;
}
void Graph::printBFS(int start)
{
    BFS(start);
    cout<<endl;
}
int main()
{
    int n,m;
    cin>>n>>m;
    Graph g(n);
    int a,b;
    for(int i=0;i<m;i++)
    {
        cin>>a>>b;
        g.addEdge(a,b);
    }
    int toDelete;
    cin>>toDelete;
    g.printDFS(0);
    g.removeVertex(toDelete);
    g.printBFS(0);
    return 0;
}

邻接表的深度优先搜索实现例: 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//邻接表存储的有向图
class Graph{
    public:
    int V;//顶点数
    vector<int> *adj;//邻接表
    Graph(int V)
    {
        this->V=V;
        adj = new vector<int>[V];
    }
    void addEdge(int v,int w)
    {
        adj[v].push_back(w);//顶点v的邻接表中添加w
    }
};
//使用深度优先搜索,求出每个顶点的出度。
void dfs(Graph*g,int v,vector<int>&visited,vector<int>&out_degree)
{
    //标记顶点v已经访问
    visited[v]=true;
    for(int w:g->adj[v])
    {
        if(!visited[w])
        {
            //遍历邻接表每个顶点w
            dfs(g,w,visited,out_degree);
        }
    }
    //递归结束,将当前顶点v的出度+1.
    out_degree[v]=out_degree[v]+1;
}
//计算每个顶点的出度
vector<int>calculateOutDegree(Graph*g)
{
    vector<int>out_degree(g->V,0);
    vector<int>visited(g->V,false);
    for(int v=0;v<g->V;v++)
    {
        if(!visited[v])
        {
            dfs(g,v,visited,out_degree);
        }
    }
    return out_degree;
}
int main()
{
    int V = 5;
    Graph g(V);
    g.addEdge(0,1);
    g.addEdge(0,2);
    g.addEdge(1,2);
    g.addEdge(2,0);
    g.addEdge(2,3);
    g.addEdge(3,3);
    g.addEdge(3,4);
    vector<int>out_degree = calculateOutDegree(&g);
    for(int v=0;v<V;v++)
    {
        cout<<"Out degree of vertex"<<v<<"is"<<out_degree[v]<<endl;
    }
    return 0;

}

下面是广度优先搜索:

#include<iostream>     // for input and output
#include<vector>       // for vectors
#include<queue>        // for queue
#include<algorithm>    // for algorithms

// Graph class represents a graph using adjacency list representation
class Graph {
public:
    int V; // Number of vertices
    vector<vector<int>> adj; // Adjacency list representation of the graph

    // Constructor
    Graph(int V) {
        this->V = V;
        adj.resize(V); // Initialize adjacency list with V empty vectors
    }

    // Adds an edge between two vertices v and w
    void addEdge(int v, int w) {
        adj[v].push_back(w); // Add w to the end of the list for v
    }
};

// BFS traverses the graph starting from vertex s
void bfs(Graph& g, int s, vector<bool>& visited) {
    queue<int> q;
    q.push(s);
    visited[s] = true;

    while (!q.empty()) {
        int v = q.front();
        q.pop();

        // Visit all adjacent vertices
        for (int w : g.adj[v]) {
            if (!visited[w]) {
                visited[w] = true;
                q.push(w);
            }
        }
    }
}

int main() {
    int V = 5; // Number of vertices in the graph
    Graph g(V);

    // Add edges to the graph
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 2);
    g.addEdge(2, 0);
    g.addEdge(2, 3);
    g.addEdge(3, 3);
    g.addEdge(3, 4);

    vector<bool> visited(V, false);

    // Perform BFS from vertex 0
    bfs(g, 0, visited);

    // Print results
    for (int v = 0; v < V; v++) {
        if (visited[v]) {
            cout << "Node " << v << " visited" << endl;
        } else {
            cout << "Node " << v << " not visited" << endl;
        }
    }

    return 0;
}

找出一条无向图的通路:

#include <iostream>
#include <stack>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
class Graph
{
    public:
    int V;
    vector<int>*adj;
    Graph(int V)
    {
        this->V=V;
        adj = new vector<int>[V];
    }
    void addEdge(int w,int v)
    {
        adj[w].push_back(v);
        adj[v].push_back(w);
    }
};
//使用深度优先搜索遍历图,判断是否有经过v的回路
bool Cycle(Graph*g,int v,vector<bool>&visited,queue<int>&q)
{
    visited[v]=true;
    for(int w:g->adj[v])
    {
        if(!visited[w])
        {
            if(Cycle(g,w,visited,q))
            {
                q.push(w);
                return true;
            }

        }
        else{
            if(w==v)
            return true;
        }
    }
    return false;
}
int main()
{
    int V=5;
    Graph g(V);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 2);
    g.addEdge(2, 0);
    g.addEdge(2, 3);
    g.addEdge(3, 3);
    g.addEdge(3, 4);
    queue <int> q;
    vector<bool> visited(V,false);
    int s;
    cin>>s;
    bool has_cycle=Cycle(&g,s,visited,q);
      if (has_cycle) {
        cout << "There is a cycle in the graph." << endl;
        cout<<s<<" ";
        while(!q.empty())
        {
            cout<<q.front()<<" ";
            q.pop();
        }
        cout<<s<<"";
    } else {
        cout << "There is no cycle in the graph." << endl;
    }

    return 0;



}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丘小羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值