从这开始有些用C++重新写了!
#include<iostream> #include<queue> #include<string> using namespace std; #define MAX 10 char str[8]={'A','C','I','M','N','P','T','U'}; int temp[MAX*3]; int str2[256][MAX*3]; string str3; class node { public: int k; char c; node *l,*r; node() { c='0'; k=0;r=l=NULL; } node(int a,char s) { k=a;r=l=NULL; c=s; } friend node* uni(node *p,node *q) { node *temp=new node(p->k+q->k,'0'); temp->l=p; temp->r=q; return temp; } }; void prim(node *p,int L) { if(!p->r) { str2[p->c][0]=L; for(int i=1;i<=L;i++) { str2[p->c][i]=temp[i-1]; } } else { temp[L]=0; prim(p->l,L+1); temp[L]=1; prim(p->r,L+1); } } class nodeCmp { public: bool operator()(node* p1, node* p2) const { return p1->k > p2->k; } }; node *s[MAX*3]; priority_queue,nodeCmp> pro_queue; int main() { int i,a; for(i=0;i<8;i++) { cin>>a; node *p; p=new node(a,str[i]); s[i]=p; pro_queue.push(s[i]); } while(pro_queue.size()>1) { node *p,*q,*k; p=pro_queue.top(); pro_queue.pop(); q=pro_queue.top(); pro_queue.pop(); k=uni(p,q); pro_queue.push(k); } node *p=pro_queue.top(); prim(p,0); for(i=0;i<8;i++) { cout<<str[i]<<": "; for(int j=1;j<=str2[str[i]][0];j++) { cout<<str2[str[i]][j]; } cout<<endl; } cin>>str3; int len=str3.length(); for(i=0;i<len;i++) { for(int j=1;j<=str2[str3[i]][0];j++) { cout<<str2[str3[i]][j]; } } cout<<endl; cin>>str3; len=str3.length(); node *q=pro_queue.top(); for(i=0;i<len;i++) { if(str3[i]=='1') { q=q->r; } else { q=q->l; } if(q->c!='0') { cout<c; q=pro_queue.top(); } } cout<<endl; return 0; }