11.26随笔

这里是11.26随笔。
题目留档:输入一组整型权值,构建哈夫曼树,实现哈夫曼编码,并输出带权路径长度。

输入格式:
第一行输入叶子结点个数,接着依次输入权值。若叶子数为0或1,则输出error

输出格式:
输出哈夫曼编码,输出带权路径长度。

代码:

include

include

include

include

typedef struct huff{
int weight;
struct huff* left=nullptr;
struct huff* right=nullptr;
struct huff* parent=nullptr;
std::string code;
}huff;
struct com{
bool operator()(const huff* a,const huff* b){
return a->weight>b->weight;
}
};
void gen(huff* node){
if(node->left!=nullptr){
node->left->code=node->code+"0";
gen(node->left);
}
if(node->right!=nullptr){
node->right->code=node->code+"1";
gen(node->right);
}
}
int main(){
int n;
std::cin>>n;
if(n0||n1){
std::cout<<"error";
return 0;
}
/std::priority_queue<huff,std::vector<huff>,com>nodes;/
std::vectorweight;
for(int i=0;i<n;++i){
int w;
std::cin>>w;
weight.push_back(w);
}
std::sort(weight.begin(),weight.end());
std::priority_queue<huff,std::vector<huff>,com>nodes;
for(int w : weight){
huff* newNode=new huff;
newNode->weight=w;
nodes.push(newNode);
}
while (nodes.size()>1){
huff* left=nodes.top();
nodes.pop();
huff* right=nodes.top();
nodes.pop();
huff* parent=new huff;
parent->weight=left->weight+right->weight;
parent->left=left;
left->parent=parent;
parent->right=right;
right->parent=parent;
nodes.push(parent);
}
huff* root=nodes.top();
gen(root);
int wpl=0;
std::vector<huff>allNodes;
std::queue<huff
> q;
q.push(root);
while (!q.empty()){
huff* cur=q.front();
q.pop();
if(cur->leftnullptr&&cur->rightnullptr){
allNodes.push_back(cur);
std::cout<weight<<"编码为"<code<<std::endl;
wpl+=cur->weight*cur->code.length();
}
if(cur->left!=nullptr){
q.push(cur->left);
}
if(cur->right!=nullptr){
q.push(cur->right);
}
}
std::cout<<"WPL:"<<wpl<<std::endl;
return 0;
}

posted @   Thanatos。syts  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示