Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<cstdio>
- #include<cstdlib>
- #include<cstring>
- using namespace std;
- int frequency[200];
- struct node
- {
- char c;
- int fre;
- node *lf,*rf;
- };
- node *store[1000],*now,*n1,*n2;
- char codes[200][50];
- void encode(node *head,char code[])
- {
- if(head->c!='0')
- {
- printf("%c %s\n",head->c,code);
- strcpy(codes[head->c],code);
- return;
- }
- char cl[50];
- strcpy(cl,code);
- strcat(cl,"0");
- encode(head->lf,cl);
- char cr[50];
- strcpy(cr,code);
- strcat(cr,"1");
- encode(head->rf,cr);
- }
- int main()
- {
- freopen("source.txt", "r", stdin);
- freopen("charcode.txt", "w", stdout);
- char c;
- int count=0,total=0,i;
- while(scanf("%c",&c)==1)
- {
- frequency[c]++;
- total++;
- }
- for(i='a';i<='z';i++)
- {
- now=(node*)malloc(sizeof(node));
- now->fre=frequency[i];
- now->c=i;
- store[count++] = now;
- }
- now=(node*)malloc(sizeof(node));
- now->fre=frequency[' '];
- now->c=' ';
- store[count++] = now;
- int elements=count-1;
- int min,minode;
- while(elements--)
- {
- min=10000000,minode=-1;
- for(i=0;i<count;i++)
- {
- if(store[i]!=NULL&&store[i]->fre<min)
- {
- min=store[i]->fre;
- minode=i;
- }
- }
- n1=store[minode];
- store[minode]=NULL;
- min=10000000,minode=-1;
- for(i=0;i<count;i++)
- {
- if(store[i]!=NULL&&store[i]->fre<min)
- {
- min=store[i]->fre;
- minode=i;
- }
- }
- n2=store[minode];
- store[minode]=NULL;
- now=(node*)malloc(sizeof(node));
- now->fre=n1->fre+n2->fre;
- now->c='0';
- now->lf=n1;
- now->rf=n2;
- store[count++]=now;
- }
- node *tree=store[count-1];
- char str[]="";
- encode(tree,str);
- freopen("source.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- while(scanf("%c",&c)==1)
- {
- printf("%s",codes[c]);
- }
- //while(1);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement