POJ 3253 Fence Repair (霍夫曼編碼 + 最小堆)

#include <stdio.h>
#define MAX_PLANKS 20000

int numOfPlanks;
long long length[MAX_PLANKS + 1];
int heapSize;

void swap(long long  *a, long long *b){
	long long c = *a;
	*a = *b;
	*b = c;
}

int getParent(int child){
	return child >> 1;
}

int leftChild(int parent){
	return parent << 1;
}

int rightChild(int parent){
	return (parent << 1) + 1;
}

void minHeapify(int parent){
	int smallest = parent;
	int left = leftChild(parent);
	if (left <= heapSize &&  length[left] < length[smallest])
		smallest = left;
	int right = rightChild(parent);
	if (right <= heapSize && length[right] < length[smallest])
		smallest = right;
	if (smallest != parent){
		swap(&length[smallest], &length[parent]);
		minHeapify(smallest);
	}
}

void buildMinHeap(){
	int parent;
	for (parent = heapSize >> 1; parent >= 1; parent--)
		minHeapify(parent);
}

long long extractMin(){
	long long min = length[1];
	length[1] = length[heapSize];
	heapSize--;
	minHeapify(1);
	return min;
}

void insert(long long len){
	heapSize++;
	length[heapSize] = len;
	int index = heapSize;
	int parent;
	while (( parent = getParent(index) ) >= 1 && length[parent] > length[index]){
		swap(&length[index], &length[parent]);
		index = parent;
	}
}

int main(){
	
	scanf("%d", &numOfPlanks);
	int i;
	for (i = 1; i <= numOfPlanks; i++)
		scanf("%d", &length[i]);

	heapSize = numOfPlanks;
	buildMinHeap();

	long long one, another;
	long long minCost = 0;
	while (heapSize > 1){
		one = extractMin();
		another = extractMin();
		minCost += one + another;
		insert(one + another);
	}

	//注意輸出long long 要用 %lld
	printf("%lld\n", minCost);

	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章