当前位置:文档之家› 算法设计与分析实验报告贪心算法

算法设计与分析实验报告贪心算法

scanf("%f",&huffmantree[i].weight);
printf("\n");
for(i=0;i<m;i++)
{
huffmantree[i].lchild=-1;
huffmantree[i].rchild=-1;
huffmantree[i].parent=-1;
}
for(count=n;count<m;count++)
算法设计与分析实验报告
贪心算法
班级:2013156学号:201315614姓名:张春 阳
哈夫曼编码
代码
#include<stdio.h>
float small1,small2;
int flag1,flag2,count;
typedef struct HuffmanTree
{
float weight;
int lchild,rchild,parent;
}huffman;
huffman huffmantree[100];
void CreatHuffmanTree(int n,int m)
{
int i;
void select();
printf("请输入%d个节点的权值:",n);
for(i=0;i<n;i++)
flag2=i;
if(small1>small2)
{
stemp=small1;
small1=small2;
small2=stemp;
ftemp=flag1;
flag1=flag2;
flag2=ftemp;
}
}
}
void huffmancode(int n)
{
int a[100];
int j,k,i,c;
{
select();
huffmantree[flag1].parent=count;
huffmantree[flag2].parent=count;
huffmantree[count].weight=small1+small2;
huffmantree[count].lchild=flag1;
huffmantree[count].rchild=flag2;
}
}
void select()
{
int i,a,b;
float stemp;
int ftemp;
a=0;b=0;
for(i=0;i<count;i++)
{
if(huffmantree[i].parent==-1)
{
if(a==0)
{
small1=huffmantree[i].weight;
flag1=i;
CreatHuffmanTree(n,m);
huffmancode(n);
}
截图
flag1=flag2;
flag2=ftemp;
}
for(i=0;i<count;i++)
if(huffmantree[i].parent==-1)
if((flag1!=i)&&(flag2!=i))
if(huffmantree[i].weight<small2)
{
small2=huffmantree[i].weight;
c=c+1;
j=k;
}
printf("节点%d的哈夫曼编码为:",i);
for(c=c-1;c>-1;c--)
printf("%d",a[c]);
printf("\n");
}
}
void main()
{
int n,m;
printf("请输入一共有几个节点:");
scanf("%d",&n);
m=2*n-1;
a=a+1;
}
else
if(b==0)
{
small2=huffmantree[i].weight;
flag2=i;
b=b+1;
}
}
if((a==1)&&(b==1))
break;
}
if(small1>small2)
{
stemp=small1;
small1=small2;
small2=stemp;
ftemp=flag1;
for(i=0;i<n;i++)
{
j=i;
c=0;
while(huffmantree[j].parent!=-1)
{
k=huffmantree[j].parent;
if(huffmantree[k].lchild==j)
a[c]=0;
if(huffmantree[k].rchild==j)
a[c]=1;
相关主题