Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

Huffman树 + 手写PQ

Posted by zhouzp15 at 2017-01-20 21:04:40 on Problem 3253
#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:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator