构造霍夫曼树
来源:互联网 发布:java 字符串截取 编辑:程序博客网 时间:2024/05/29 03:30
#include<iostream>#include<vector>#include<string>#include<algorithm>using namespace std;struct node{ int val; struct node *left; struct node *right; node(int i) : val(i), left(NULL), right(NULL){ }};int fun(node *root, int time){ if (root->left == NULL && root->right == NULL){ return time * root->val; } return fun(root->left, time + 1) + fun(root->right, time + 1);}int main(){ string str; while (cin >> str){ vector<int> table(256); for (int i = 0; i < str.size(); ++i) table[str[i]]++; vector<int> value; for (int i = 0; i < 256; ++i){ if (table[i]) value.push_back(table[i]); } sort(value.begin(), value.end()); vector<int> temp; vector<node *> tempNode; temp.push_back(value[0] + value[1]); node *a = new node(value[0]); node *b = new node(value[1]); node *c = new node(value[0] + value[1]); c->left = a; c->right = b; tempNode.push_back(c); int i = 2, j = 0; for (int k = 2; k < value.size(); ++k){ int oldI = i; int time = 0; while (time < 2){ if (i < value.size()){ if (j < temp.size()){ if (value[i] < temp[j]) i++; else j++; } else i++; } else j++; ++time; } if (i - oldI == 0){ a = tempNode[j - 1]; b = tempNode[j - 2]; } else if (i - oldI == 1){ a = tempNode[j - 1]; b = new node(value[i - 1]); } else{ a = new node(value[i - 1]); b = new node(value[i - 2]); } c = new node(a->val + b->val); c->left = a; c->right = b; tempNode.push_back(c); temp.push_back(c->val); } node *head = tempNode.back(); cout << fun(head, 0) << endl; } return 0;}
求带权路径:#include <cstdio>#include <cstring>#include <cstdlib>#include <cmath>#include <algorithm>#include <utility>#include <queue>using namespace std;int main(){ char s[3300]; while(scanf("%s",s) != EOF){ int n = strlen(s); sort(s,s + n); priority_queue<int> heap; int cnt = 0; for(int i = 0,j;i < n;){ j = i; while(j < n && s[j] == s[i]) ++ j; heap.push(i - j); i = j; ++ cnt; } int ret = 0; for(int i = 0;i < cnt - 1;++ i){ int A = heap.top(); heap.pop(); int B = heap.top(); heap.pop(); ret -= A + B; heap.push(A + B); } printf("%d\n",ret); } return 0;}
0 0
- 构造霍夫曼树
- 构造霍夫曼树代码
- 构造
- 构造
- 构造
- 构造
- 构造
- 构造
- 构造、拷贝构造、析构
- 构造器(构造方法)
- 构造、拷贝构造、赋值
- 构造方法/构造器
- 拷贝构造 赋值构造
- 构造中调用构造
- 构造方法 构造器 构造函数
- 构造解决方案
- 构造函数
- 构造器
- leetcode刷题之旅——66Plus One
- IOS开发通信录
- 四、关于Java、Android编程平台的搭建问题讲解之环境配置
- UVA 5096 求两圆柱相交体积
- JS与Android互调
- 构造霍夫曼树
- 标准C++中的string类的用法总结
- android系统的手机文件夹目录详解
- 事件的传递机制
- CodeForces 292D Connected Components (并查集+YY)
- UML简介
- CSU 1808 地铁【最短路变形】
- Node.js技术原理
- 大数据IMF传奇行动绝密课程第56课:揭秘Spark SQL和DataFrame的本质