Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- int freq[200];
- struct node
- {
- int fr;
- char c;
- char str[50]={NULL};
- struct node *lchild, *rchild;
- };
- int count=0;
- struct node *a[2700];
- int ll=0;
- char huff[27][1000];
- int min()
- {
- int b,d;
- b=9999999;
- for(int i=0;i<count;i++)
- {
- if(a[i]!=NULL&&a[i]->fr>0)
- {
- if(b>a[i]->fr)
- {
- b=a[i]->fr;
- d=i;
- }
- }
- }
- return d;
- }
- void huffman()
- {
- int p;
- struct node *x,*y,*temp;
- while(ll>1)
- {
- p=min();
- x=a[p];
- a[p]=NULL;
- p=min();
- y=a[p];
- a[p]=NULL;
- temp=(struct node*)malloc(sizeof(struct node));
- temp->lchild=x;
- temp->rchild=y;
- temp->fr=x->fr+y->fr;
- a[count++]=temp;
- ll--;
- }
- }
- void recur(struct node *root,char stemp[50])
- {
- strcpy(root->str,stemp);
- char a[50];
- strcpy(a,stemp);
- if(root->lchild==NULL&&root->rchild==NULL)
- {
- printf("%c %s\n",root->c,root->str);
- return;
- }
- strcat(a,"0");
- recur(root->lchild,a);
- strcpy(a,stemp);
- strcat(a,"1");
- recur(root->rchild,a);
- }
- void searc(struct node *root, char x )
- {
- if(root->c==x)
- {
- printf("%s",root->str);
- return;
- }
- else if(root->lchild==NULL&&root->rchild==NULL)
- return;
- searc(root->lchild,x);
- searc(root->rchild,x);
- }
- int main()
- {
- char ch;
- freopen("input.txt","r",stdin);
- freopen("out.txt","w",stdout);
- int total=0;
- while(scanf("%c", &ch)==1)
- {
- if(ch>='A'&&ch<='Z')
- freq[ch+32]++;
- else
- freq[ch]++;
- total++;
- }
- struct node *now;
- now=(struct node*)malloc(sizeof(struct node));
- now->c=' ';
- now->fr=freq[' '];
- now->lchild=NULL;
- now->rchild=NULL;
- a[count++]=now;
- printf(" : %d\n",freq[' ']);
- for(int j='a';j<='z';j++)
- {
- now=(struct node*)malloc(sizeof(struct node));
- now->c=j;
- now->fr=freq[j];
- now->lchild=NULL;
- now->rchild=NULL;
- a[count++]=now;
- printf("%c : %d\n",j,freq[j]);
- }
- for(int k=0;k<count;k++)
- {
- if(a[k]!=NULL&&a[k]->fr>0)
- {
- ll++;
- }
- }
- huffman();
- char st[10]={NULL};
- recur(a[count-1],st);
- printf("%d %d\n",total,a[count-1]->fr);
- printf("huffman string:\n");
- freopen("input.txt","r",stdin);
- while(scanf("%c",&ch)==1)
- {
- searc(a[count-1],ch);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement