http://ac.jobdu.com/problem.php?pid=1172
這道題原來做過可是一點印象都沒有,竟然還是能想到用priority_queue來做,看來之前的練習還是有效果。其實今年考研408的算法題與這道題類似,但我當時並不知道這個結論:哈夫曼樹所有葉節點的權重之和等於所有非葉結點的值的和,所以當時費了大量的時間做那道題,以至於組成原理的兩道大題幾乎完全沒做,想想就心痛。不過如今逆襲了,也算比較心安。因爲構造哈夫曼樹的時候總是要取兩個權值最小的結點,構造好的新非葉結點又要重新放回去篩選,如果反覆排序會大大增加時間複雜度,所以用小頂堆解決這個問題就會容易許多,即用STL裏的priority_queue來實現。代碼如下:
#include <stdio.h>
#include <queue>
using namespace std;
priority_queue <int,vector<int>,greater<int> > q; //聲明小頂堆
int main()
{
int n;
while (scanf("%d",&n)!=EOF)
{
while (!q.empty()) q.pop();
for (int i=0;i<n;++i)
{
int x;
scanf("%d",&x);
q.push(x);
}
if (n==1)
{
printf("%d\n",q.top());
continue;
}
int ans=0;
while(q.size()>1)
{
int temp=q.top();
q.pop();
temp+=q.top();
q.pop();
ans+=temp;
q.push(temp);
}
printf("%d\n",ans);
}
return 0;
}