文章标题【树】哈夫曼树
来源:互联网 发布:男科网络预约挂号 编辑:程序博客网 时间:2024/05/16 10:20
【树】哈夫曼树(一)
Time Limit:1000MS Memory Limit:65536K
Total Submit:85 Accepted:55
Description
假设用于通信的电文仅由8个字母组成,字母在电文中出现的频率分别为7、19、2、6、32、3、21、10。试为这8个字母设计哈夫曼编码。如果用二进制数表示这8个字母的编码方案.(请按照左子树根节点的权小于等于右子树根节点的权的次序构造)
Input
第一行为字母的个数n;
第二行至第n+1行分别为各个字母在电文中出现的频率;
Output
按照中序遍历输出各个编码
Sample Input
8
7
19
2
6
32
3
21
10
Sample Output
19:00
21:01
2:10000
3:10001
6:1001
7:1010
10:1011
32:11
很模版的哈夫曼编码问题,基本照着模版写就是对的
代码如下(C)
#include <cstdio>#include <string>using namespace std;struct arr{ int d,lc,rc,ad;}; arr f[1000],a[1000];int paixu(int k)//这个很蠢的排序实际上c++不用这 么打的,但是我初学不太会{ arr t[1000]; for (int i=1;i<=k;i++) for (int j=i+1;j<=k;j++) if (a[i].d>a[j].d) { t[1]=a[i]; a[i]=a[j]; a[j]=t[1]; } return 0; }int vist(int x,string ch){ if (f[x].d==0) return 0; vist(f[x].lc,ch+"0"); vist(f[x].rc,ch+"1"); if (f[x].lc==0&&f[x].rc==0) printf("%d:%s\n",f[x].d,ch.c_str())//这个字符串输出其实我不是很懂,只是一开始没加后面的.c_str()一直不行,然后问了一个比较懂得。。他说加上就好了。。。; return 0;}int main(){ int n; scanf("%d",&n); for (int i=1;i<=n;i++) { scanf("%d",&a[i].d); f[i].d=a[i].d; a[i].ad=i; } int t=n+1,i=n; while (i>1)//建树 { paixu(i); f[t].d=a[1].d+a[2].d; f[t].lc=a[1].ad; f[t].rc=a[2].ad; a[1].d=f[t].d; a[1].ad=t; a[2].d=a[i].d; a[2].ad=a[i].ad; t++; i--; } vist(t-1,"");}
0 0
- 文章标题【树】哈夫曼树
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- Spring 初探(五)(Spring Bean 自动装配与自定义监听事件)
- Leetcode Reverse Words in a String 151
- 2015-2016年iOS开发经验总结
- iOS相册权限、相机权限、麦克风权限
- bzoj 1741: [Usaco2005 nov]Asteroids 穿越小行星群
- 文章标题【树】哈夫曼树
- 带你快速玩转canvas(7)保存画笔状态和恢复画笔状态
- codeforce #387 D. Winter Is Coming
- 第3章 基本概念(4)操作符:一元操作符......
- 【OpenSource】【图片加载】Google 推荐的图片加载开源框架 Glide
- 给samba的文件服务器启用回收站功能
- Android 技术之Glide和Picasso
- tomcat下配置https环境(windows环境)
- OAuth 2.0 授权原理