#include <iostream>
#include <string.h>
#include <fstream>
#include <queue>
#include <stack>
using namespace std;
int a[26];
char s[1005];
int len;
struct Node
{
int id;
char data;
int w;
int parent,Lchild,Rchild;
char code[1005];
}num[50005];
bool operator < (const Node &a,const Node &b)
{
return a.w>b.w;
}
priority_queue<Node> q;
void Select(int *s1,int *s2)
{
*s1=q.top().id;
q.pop();
*s2=q.top().id;
q.pop();
}
void Creat()
{
int n=0,m;
for(int i=0;i<26;i++)
{
if(a[i]!=0)
{
num[++n].data=i+'A';
num[n].id=n;
num[n].Lchild=0;
num[n].parent=0;
num[n].Rchild=0;
num[n].w=a[i];
q.push(num[n]);
}
}
m=2*n-1;
len=n;
for(int i=n+1;i<=m;i++)
{
num[i].id=i;
num[i].Lchild=0;
num[i].parent=0;
num[i].Rchild=0;
num[i].w=0;
}
for(int i=n+1;i<=m;i++)
{
int s1,s2;
Select(&s1,&s2);
num[s1].parent=i;
num[s2].parent=i;
num[i].Lchild=s1;
num[i].Rchild=s2;
num[i].w=num[s1].w+num[s2].w;
q.push(num[i]);
}
}
void Code()
{
int i,j,k;
stack<char> s;
for(int i=1;i<=len;i++)
{
for(j=i,k=num[i].parent;k!=0;j=k,k=num[k].parent)
{
if(j==num[k].Lchild)
{
s.push('0');
}
else
{
s.push('1');
}
}
int c=0;
while(!s.empty())
{
num[i].code[c++]=s.top();
s.pop();
}
num[i].code[c]='\0';
}
}
void Write()
{
ofstream writef("Code.txt");
cout<<"len="<<len<<endl;
for(int i=1;i<=len;i++)
{
cout<<num[i].data<<"编码:"<<num[i].code<<endl;
writef<<num[i].data<<"编码:"<<num[i].code;
writef<<endl;
}
cout<<endl;
writef.close();
writef.open("ResultFile.txt");
cout<<"原文件编码:";
for(int i=0;i<strlen(s);i++)
{
char c=s[i];
for(int j=1;j<=len;j++)
{
if(c==num[j].data)
{
writef<<num[j].code;
cout<<num[j].code;
}
}
}
cout<<endl;
writef.close();
}
int main()
{
memset(a,0,sizeof(a));
len=0;
ifstream readf("SourceFile.txt");
while(!readf.eof())
{
readf.getline(s,100);
}
readf.close();
cout<<"读取文件内容:"<<s<<endl;
for(int i=0;i<strlen(s);i++)
{
int k=s[i]-'A';
a[k]++;
}
Creat();
Code();
Write();
return 0;
}