1. 程式人生 > 實用技巧 >POJ1521(哈夫曼編碼)(貪心+優先佇列)

POJ1521(哈夫曼編碼)(貪心+優先佇列)

地址:http://poj.org/problem?id=1521

題意:

就是給定一個串,求原長度和哈夫曼編碼後的長,並求比值

解析:

並不需要構建哈夫曼樹,由於構建哈夫曼樹的過程,是每次找佇列中最小的兩個進行合併,所以定義一個小為頭的優先佇列,每次取最小的兩個,累加後,再相加放回去。

G++會WA,用C++交

#include<iostream>
#include<cstring>
#include<stack>
#include<queue>
#include<cstdio>
#include<vector>
#include
<algorithm> using namespace std; typedef long long ll; const int maxn=1e3+50; char s[maxn]; int ch[29]; //priority_queue<int, vector<int>, greater<int> > Q; 最小的在隊首 int main() { while(scanf("%s",s)) { int len=strlen(s); if(len==3&&s[0]=='E'&&s[1
]=='N'&&s[2]=='D') break; sort(s,s+len); int cnt=1; priority_queue<int, vector<int>, greater<int> > Q; for(int i=1;i<len;i++) { if(s[i]!=s[i-1]) { Q.push(cnt); cnt
=1; } else cnt++; } int sum=0; Q.push(cnt);  //最後會漏掉一個 if(Q.size()==1)  //字串只有一種的情況。 sum=Q.top(); while(Q.size()>1) { int a=Q.top();Q.pop(); int b=Q.top();Q.pop(); sum+=a+b; Q.push(a+b); } // if(sum==0) // sum=Q.top(); printf("%d %d %.1lf\n",len*8,sum,(double)(len*8*1.0)/(sum*1.0)); } }