rt,
原link (这是重新发)
#include<iostream>
#include<string.h>
#include<queue>
#include<climits>
#include<algorithm>
#include<vector>
using namespace std;
int a[65] = {};
string s[65] = {};
string ans[1005] = {};
bool mark[1005] = {};
int n,sum=0,WPL=0,proWPL=0;
string awa;
struct lrt{
int father=0;
int ltree=0,rtree=0;
};
struct tree{
int root=0;
lrt vec[1005] = {};
};
vector<tree> que;
tree huffman;
bool cmp(tree a,tree b){
return a.root<b.root;
}
tree create_hufftree(){
int size = n,st = 0;
for(int i=1;i<=n;++i){
tree tmp;
tmp.root = a[i];
que.push_back(tmp);
}
while(size>1){
sort(que.begin(),que.end(),cmp);//排序选两个最小的
tree qfra = que[st];
st++,size--;
tree qfrb = que[st];
st++,size--;
tree ntr;
ntr.root = qfra.root+qfrb.root;
lrt tmplr;
tmplr.ltree = qfra.root , tmplr.rtree = qfrb.root;
ntr.vec[ ntr.root ] = tmplr;
// cout<<ntr.vec[ ntr.root ].ltree<<" "<<ntr.vec[ ntr.root ].rtree<<" "<<ntr.root<<"\n";
for(int i=0;i<=sum;++i){
if(i==ntr.root) continue;
if(ntr.vec[i].ltree!=0 && ntr.vec[i].rtree!=0) continue;
ntr.vec[i] = qfra.vec[i];
}
for(int i=0;i<=sum;++i){
if(i==ntr.root) continue;
if(ntr.vec[i].ltree!=0 && ntr.vec[i].rtree!=0) continue;
ntr.vec[i] = qfrb.vec[i];
}
que.push_back(ntr);
size++;
}
return que[st];
}
void dfs(int idx,string str){
if(mark[idx]==true){
ans[idx] = str;
return ;
}
if(huffman.vec[idx].ltree==0 && huffman.vec[idx].rtree==0){
return ;
}
dfs(huffman.vec[idx].ltree,str+'0');
dfs(huffman.vec[idx].rtree,str+'1');
}
int main(){
freopen("huffman.in","r",stdin);
freopen("huffman.out","w",stdout);
cin>>n;
for(int i=1;i<=n;++i){
cin>>a[i];
sum += a[i];
mark[a[i]] = true;
}
for(int i=1;i<=n;++i){
cin>>s[i];
}
huffman = create_hufftree();
dfs(huffman.root,awa);
for(int i=1;i<=n;++i){
WPL += (a[i]*ans[a[i]].length());
}
for(int i=1;i<=n;++i){
proWPL += (a[i]*s[i].length());
}
if(WPL==proWPL){
cout<<"Yes"<<"\n";
cout<<WPL<<"\n";
}else{
if(n==1 && s[1].length()==1){
cout<<"Yes"<<"\n";
cout<<proWPL<<"\n";
}else{
cout<<"No"<<"\n";
for(int i=1;i<=n;++i){
cout<<ans[a[i]]<<"\n";
}
}
}
// cout<<"Yes"<<"\n";
// cout<<ans<<"\n";
/*
for(int i=0;i<=sum;++i){
cout<<"root="<<i<<" : ";
cout<<huffman.vec[i].ltree<<" "<<huffman.vec[i].rtree<<"\n";
}*/
return 0;
} //文章长度 = \SUM a_i*s_i.length
(我的这份代码没判题目输入的哈夫曼前缀是否相等,但是只能 WA ,应该不能 RE )
报错信息如下所示:
--------------------
Segmentation fault.
#0 0x00001555549784cd in __memmove_avx_unaligned_erms_rtm ()
from /nix/glibc-2.39-52/lib/libc.so.6
#1 0x0000000000401e95 in create_hufftree ()
at /nix/gcc/include/c++/13.3.0/bits/stl_vector.h:1126
1126 operator[](size_type __n) _GLIBCXX_NOEXCEPT
#2 0x00000000004012c9 in main () at foo.cc:94
94 huffman = create_hufftree();
希望能指点啊啊啊,谢谢