noj 1491 Huffman Coding
哈夫曼编码
#include<iostream> #include<queue> #include<vector> using namespace std; const int Max = 2001; struct Tode { int id; int weight; }; struct node{ int left , right ; int weight; }p[Max]; int tail,root,ans; struct cmp{ bool operator() ( Tode a, Tode b ){ return a.weight>b.weight; } }; priority_queue<Tode,vector<Tode>, cmp > pq; void creatree(int n){ for(;;){ if(pq.size()==1) { root = pq.top().id; break; } Tode A = pq.top(); pq.pop(); Tode B = pq.top(); pq.pop(); Tode C ; C.id = tail++; C.weight= A.weight +B.weight; pq.push(C); p[C.id].left = A.id; p[C.id].right = B.id; } } void dfs(int u,int dept){ if(p[u].weight!=-1){ ans+= p[u].weight*dept; } if(p[u].left!=-1){ dfs(p[u].left,dept+1); } if(p[u].right!=-1){ dfs(p[u].right,dept+1); } } int main(){ int n,i; for(;cin>>n;){ tail = n; ans = 0 ; for(i=0;i<2*n;i++) { p[i].left = -1; p[i].right = -1; p[i].weight = -1; } for(;!pq.empty();) pq.pop(); for(i=0;i<n;i++){ Tode B; cin>>B.weight; B.id = i; p[i].weight = B.weight; pq.push(B); } if(n==1|| n==0) { printf("%d\n",n*pq.top().weight); continue; } creatree(n); dfs(root,0); printf("%d\n",ans); } return 0; }