哈夫曼树
来源:互联网 发布:screw it,let's do it 编辑:程序博客网 时间:2024/05/29 02:17
点击打开链接
输入:
输入有多组数据。
每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。
输出:
输出权值。
样例输入:
5
1 2 2 5 9
样例输出:
37
题解:建立优先队列 (小优先),取最小的两个,求和,再入队循环
代码:
/*******************不建树****************************/
#include<stdio.h>#include<stack>#include<queue>#include<algorithm>#include<iostream>using namespace std;int main(){int n,i;priority_queue <int,vector<int>,greater<int> > qu;//优先队列 小优先 while(cin>>n){int w;for(i=0;i<n;i++){cin>>w;qu.push(w);}int ans=0;while(qu.size()!=1){int a,b,add;a=qu.top();qu.pop();b=qu.top();qu.pop();add=a+b;ans+=add;qu.push(add);}qu.pop();//清空队列,防止下次出错 cout<<ans<<endl;}return 0;}
/**************************输入一串字符adadsajkf,求出曼哈顿序列**************************/#include<stdio.h> #include<string.h> #include<stdlib.h> #define maxvalue 0x7fffffff struct huffman { int weight; int parent,lchild,rchild; }list[5000]; int main() { int n,m; int i,j; int ans; int x1,x2; int m1,m2; while(scanf("%d",&n)!=EOF) { m=2*n-1; for(i=0;i<m;i++) list[i].parent=list[i].lchild=list[i].rchild=-1; for(i=0;i<n;i++) scanf("%d",&list[i].weight); ans=0; for(i=0;i<n-1;i++) { x1=x2=0; m1=m2=maxvalue; for(j=0;j<n+i;j++) { if(list[j].weight<m1&&list[j].parent==-1) { x2=x1; m2=m1; x1=j; m1=list[j].weight; } else if(list[j].weight<m2&&list[j].parent==-1) { x2=j; m2=list[j].weight; } } list[x1].parent=n+i; list[x2].parent=n+i; list[n+i].lchild=x1; list[n+i].rchild=x2; list[n+i].weight=list[x1].weight+list[x2].weight; ans+=list[n+i].weight; } printf("%d\n",ans); } return 0; }
阅读全文
0 0
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- 哈夫曼树
- Spring Boot 整合 Elasticsearch,实现 function score query 权重分查询
- 2016年Java面试题整理
- Error:(3) Error: "app_name" is not translated in "zh" (Chinese) [MissingTranslation]
- Postgresql允许远程访问配置修改
- 彻底理解ThreadLocal
- 哈夫曼树
- ubuntu修改时区和时间的方法
- android px dp 互换工具
- 百练_3195:最大公约数
- 使用jQuery.form插件,实现完美的表单异步提交
- 记Dorado7学习(4)
- 浏览器处理JS的线程
- Linux基础命令学习
- 队列queue的详细讲解