九度oj 题目1172:哈夫曼树
2024-09-07 19:45:10
- 题目描述:
-
哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和。
- 输入:
-
输入有多组数据。
每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。
- 输出:
-
输出权值。
- 样例输入:
-
5
1 2 2 5 9
- 样例输出:
-
37 权值为层数,从0开始,一开始本来想用数组来构造哈夫曼树,代码如下:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm> #define MAX 1009
#define HMAX 2009 struct Haff
{
int level;
int key;
bool isLeaf;
};
Haff haff[MAX]; int cmp(const void* a, const void *b) {
Haff at = *(Haff *)a;
Haff bt = *(Haff *)b;
if(at.key != bt.key)
return at.key - bt.key;
else if(at.isLeaf == bt.isLeaf) {
return ;
}
else {
if(at.isLeaf == true) {
return ;
}
else {
return -;
}
}
} int max(int a, int b) {
return a > b ? a: b;
}
int main(int argc, char const *argv[])
{
int n;
while(scanf("%d",&n) != EOF) {
for(int i = ; i < n; i++) {
scanf("%d",&haff[i].key);
haff[i].level = ;
haff[i].isLeaf = true;
}
int ptr = ;
int count = n;
int cen;
int N = * n - ;
while(ptr < N - ) {
qsort(&haff[ptr],count-ptr, sizeof(Haff), cmp); int pj = ptr + ;
cen = max(haff[ptr].level, haff[pj].level);
haff[ptr].level = cen;
haff[pj].level = cen;
haff[count].key = haff[ptr].key + haff[pj].key;
haff[count].level = cen + ;
haff[count].isLeaf = false;
count++;
ptr = ptr + ;
} int sum = ;
cen = haff[N-].level; /*for(int i = 0; i < count; i++) {
printf("%d %d\t",haff[i].key, haff[i].level);
}
printf("\n");*/
for(int i = ; i < count; i++) {
if(haff[i].isLeaf == true) {
sum = sum + (cen - haff[i].level) * haff[i].key;
}
}
printf("%d\n",sum);
}
return ;
}但这样做,level的值会出现错误。
后来发现去计算答案根本不需要建树,代码如下:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm> #define MAX 1009 int haff[MAX]; int cmp(const void* a, const void *b) {
int at = *(int *)a;
int bt = *(int *)b;
return at - bt; } int max(int a, int b) {
return a > b ? a: b;
}
int main(int argc, char const *argv[])
{
int n;
while(scanf("%d",&n) != EOF) {
for(int i = ; i < n; i++) {
scanf("%d",&haff[i]);
}
int ptr = ;
int count = n;
int N = * n - ;
int sum = ;
while(ptr < N - ) {
qsort(&haff[ptr],count-ptr, sizeof(int), cmp); int pj = ptr + ;
haff[count] = haff[ptr] + haff[pj];
sum = sum + haff[count];
count++;
ptr = ptr + ;
}
printf("%d\n",sum);
}
return ;
}
最新文章
- Oracle读取excel
- register_shutdown_function AND fastcgi_finish_request
- Android复制Assets目录下的文件到指定目录
- git version 2.5.0.windows.1中文乱码问题解决方案
- rmmod 无法卸载模块问题
- 运输层协议----UDP
- CentOS 7 之Shell学习笔记
- Linux系统启动流程及grub重建(1)
- 为Exchange 2007 SCC 启用 SCR 副本-供需要的人使用!
- 1734: [Usaco2005 feb]Aggressive cows 愤怒的牛
- centos上发布部署python的tornado网站项目完整流程
- 渗透测试平台bwapp简单介绍及安装
- Python 汉诺塔游戏
- Windows Server 2012开启磁盘性能计数器
- JSTL安装与使用
- Windows上只复制目录结构不复制文件
- more和less命令详解
- 怎么调用html5的摄像头,录音,视频?
- Hive查看执行日志
- JS中关于换行的2个坑