| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
Huffman树 + 手写PQ#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
const int N = 2e4 + 5;
typedef long long LL;
int a[N], n;
class PQ
{
int _heap[N], _size;
#define p(x) (x >> 1)
#define lc(x) (x << 1)
#define rc(x) ((x << 1) | 1)
int properParent(int i)
{
int ret;
ret = (lc(i) <= _size) ? (_heap[i] < _heap[lc(i)] ? i : lc(i)) : i;
ret = (rc(i) <= _size) ? (_heap[ret] < _heap[rc(i)] ? ret : rc(i)) : ret;
return ret;
}
void pushDown(int i)
{
int j;
while (i != (j = properParent(i)))
swap(_heap[i], _heap[j]), i = j;
}
void pushUp(int i)
{
while (p(i) > 0)
{
int j = p(i);
if (_heap[j] < _heap[i]) break;
swap(_heap[i], _heap[j]); i = j;
}
}
public:
PQ(int n) : _size(n)
{
for (int i = 1; i <= n; i++) scanf("%d", _heap + i);
for (int i = p(n); i > 0; i--)
pushDown(i);
}
int size() { return _size; }
int insert(int x)
{
_heap[++_size] = x;
pushUp(_size);
}
int delMax()
{
int ret = _heap[1];
swap(_heap[1], _heap[_size--]);
pushDown(1);
return ret;
}
};
int main()
{
scanf("%d", &n);
PQ pq(n);
LL ans = 0;
while (pq.size() > 1)
{
int min1 = pq.delMax(), min2 = pq.delMax();
int combine = min1 + min2;
ans += combine; pq.insert(combine);
}
printf("%lld\n", ans);
fclose(stdin);
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator