pku 3253 Fence Repair 优先队列实现哈夫曼树

http://poj.org/problem?id=3253

View Code
#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
#define maxn 20007
using namespace std;

struct cmp
{
bool operator() (int &a,int &b)
{
return a > b;
}
};
int main()
{
priority_queue<int,vector<int>,cmp>q;
int n,i,sum,a;
while (~scanf("%d",&n))
{
while (!q.empty()) q.pop();
for (i = 0; i < n; ++i)
{
scanf("%d",&a);
q.push(a);
}
sum = 0;
while (!q.empty())
{
int x = q.top(); q.pop();
int y = q.top(); q.pop();
//printf("%d %d\n",x,y);
sum += (x+y);
if (!q.empty())
q.push(x + y);
}
printf("%d\n",sum);
}
}



posted @ 2012-03-31 11:25  E_star  阅读(222)  评论(0编辑  收藏  举报