对字符串进行二进制编码(哈夫曼算法)

在清理我的桌面,发现了一串神秘的代码

原来是之前帮朋友写的数据结构作业啊

任务一:给定英文字母字符集及使用频率,进行最优不等长二进制编码,得出方案

任务二:基于所设计的二进制编码,输入任意字符,输出二进制编码字符串

任务三:任务二对调

步骤一:读入字符集和频率,排个序。文档字符集命名为1.txt

a	8.167%	h	6.094%	o	7.507%	u	2.758%
b	1.492%	i	6.966%	p	1.929%	v	0.978%
c	2.782%	j	0.153%	q	0.095%	w	2.360%
d	4.253%	k	0.772%	r	5.987%	x	0.150%
e	12.702%	l	4.025%	s	6.327%	y	1.974%
f	2.228%	m	2.406%	t	9.056%	z	0.074%
g	2.015%	n	6.749%		

第二步:哈夫曼算法,并输出编码

a 0111 0111
b 000011 000011
c 10010 10010
d 11111 11111
e 001 001
f 10100 10100
g 110011 110011
h 0110 0110
i 1101 1101
j 110100100 110100100
k 1100100 1100100
l 01111 01111
m 11100 11100
n 0101 0101
o 1011 1011
p 100011 100011
q 100100100 100100100
r 1010 1010
s 1110 1110
t 000 000
u 00010 00010
v 000100 000100
w 01100 01100
x 010100100 010100100
y 010011 010011
z 000100100 000100100

第三步:按照任务二和任务三的要求匹配编码

#include
#include
#include
#include
#include
using namespace std;
const int N = 1e5 + 10;
pairp[26];
priority_queue, vector>, greater>>q;
int fa[N], sonl[N], sonr[N];
mapmp1;
mapmp2;
int main()
{
	FILE* fp;
	fp=freopen("1.txt", "r", stdin);
	//freopen("2.txt", "w", stdout);
	double ans = 0;
	for (int i = 0; i < 26; i++)
	{
		char x, z;
		double t;
		cin >> x >> t >> z;
		p[i].first = t * 1000;
		p[i].second = x - 'a';
		q.push(p[i]);
	}
	int cnt = 26;
	while (q.size() > 1)
	{
		pairk1;
		pairk2;
		k1 = q.top();
		q.pop();
		k2 = q.top();
		q.pop();
		sonl[cnt] = k1.second;
		sonr[cnt] = k2.second;
		fa[k1.second] = cnt;
		fa[k2.second] = cnt;
		k1.first += k2.first;
		k1.second = cnt;
		q.push(k1);
		cnt++;
	}
	cout << "字符集的二进制编码方案如下:\n";
	for (int i = 0; i < 26; i++)
	{
		char x = 'a' + i;
		string s;
		s.clear();
		cout << x << " ";
		int n = i;
		while (fa[n] != 0)
		{
			if (sonl[fa[n]] == n)
			{
				s.push_back('0');
			}
			else
			{
				s.push_back('1');
			}
			n = fa[n];
		}
		reverse(s.begin(), s.end());
		mp1[x] = s;
		mp2[s] = x;
		cout <<" " << s << "\n";

	}
	freopen("CON", "r", stdin);
	while (1)
	{
		cout << "选择转换的模式(输入 1 or 2 )\n";
		cout << "1:源字符串转二进制编码字符串 2:二进制编码字符串转源字符串\n";
		string k;
		cin >> k;
		if (k != "1" && k != "2") {
			cout << "输入非法!\n";
			continue;
		}
		if (k == "1")
		{
			cout << "请输入需要编码的源字符串(仅包含字符集中的字符),回车确认:\n";
			string s,t;
			s.clear();
			t.clear();
			bool flag = 0;
			cin >> s;
			
			for (int i = 0; i < s.size(); i++)
			{
				if(s[i]>='a'&&s[i]<='z')
				t.append(mp1[s[i]]);
				else
				{
					flag = 1;
					break;
				}
			}
			if (flag == 1)cout << "输入非法!\n";
			else
			{
				cout << "字符串"<> s;
			for (int i = 0; i < s.size(); i++)
			{
				o.push_back(s[i]);
				if (mp2[o] != 0)
				{
					t.push_back(mp2[o]);
					o.clear();
				}
			}
			if(o.size()>0)cout << "输入非法!\n";
			else
			{
				cout << "编码字符串" << s << "的源字符串为:" << t << "\n";
			}
		}
		
	}
}

你可能感兴趣的:(yeah的代码学习,算法,c++,c语言)