poj3253

利用priority_queue模拟霍夫曼树。注意结果要用long long.

View Code
#include < cstdio >
#include
< iostream >
#include
< cstdlib >
#include
< cstring >
#include
< queue >
using namespace std;

struct Integer
{
long long x;
Integer(
long long xx):x(xx)
{}
};

bool operator < ( const Integer & a, const Integer & b)
{
return a.x > b.x;
}

int main()
{
// freopen("D:\\t.txt", "r", stdin);
int n;
scanf(
" %d " , & n);
priority_queue
< Integer > pq;
for ( int i = 0 ; i < n; i ++ )
{
int a;
scanf(
" %d " , & a);
pq.push(Integer(a));
}
long long ans = 0 ;
while ( 1 )
{
Integer sum(
0 ), sum2( 0 );
sum
= pq.top();
pq.pop();
if (pq.empty())
break ;
sum2
= pq.top();
pq.pop();
pq.push(Integer(sum.x
+ sum2.x));
ans
+= sum.x + sum2.x;
}
printf(
" %I64d\n " , ans);
return 0 ;
}

你可能感兴趣的:(poj)