poj3253
利用priority_queue模拟霍夫曼树。注意结果要用long long.
View Code
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <queue>
usingnamespace std;
struct Integer
{
longlong x;
Integer(longlong xx):x(xx)
{}
};
booloperator< (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));
}
longlong 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);
return0;
}
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <queue>
usingnamespace std;
struct Integer
{
longlong x;
Integer(longlong xx):x(xx)
{}
};
booloperator< (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));
}
longlong 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);
return0;
}