⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 maxheap.cpp

📁 大顶堆实现一个优先队列。对于队列的操作应该至少支持下列几种指令: Void enqueue[int ObjectID, int Priority] Int dequeue[]
💻 CPP
字号:
#include "Maxheap.h"

void  Maxheap::siftdown(int pos) {
	while(!isLeaf(pos)) {
		int j = leftChild(pos);int rc = rightChild(pos);
		if((rc<n)&&(heap[j].priority<heap[rc].priority))
			j = rc;
		if(heap[pos].priority>=heap[j].priority) break ;
		else {swap(pos,j); pos = j; }	
	}	
}

bool Maxheap::enqueue(Object o) {
	if (n>=size) return false;
	int curr = n++;
	heap[curr] = o;
	while((curr!=0)&&heap[curr].priority>heap[parent(curr)].priority) {
		swap(curr,parent(curr)); 
		helpMap(curr);
		curr = parent(curr);
	}
	helpMap(curr);
	return true;
}

int Maxheap::dequeue() {
	if(n==0) return -1;
	swap(0,--n);
	int	pos=0;
	if(n!=0)
		while(!isLeaf(pos)) {
		int j = leftChild(pos);int rc = rightChild(pos);
		if((rc<n)&&(heap[j].priority<heap[rc].priority))
			j = rc;
		if(heap[pos].priority>=heap[j].priority) break;
			else {swap(pos,j); helpMap(pos);pos = j; }	
		}
	helpMap(pos);
	nullMap(heap[n].ID);
	return heap[n].ID;
}

void Maxheap::changeWeight(Object o) {
	int pos = map[o.ID];
//	 down
	heap[pos].priority=o.priority;
	while(!isLeaf(pos)) {
		int j = leftChild(pos);int rc = rightChild(pos);
		if((rc<n)&&(heap[j].priority<heap[rc].priority))
			j = rc;
		if(heap[pos].priority>=heap[j].priority) break;
			else {swap(pos,j); helpMap(pos);pos = j; }	
		}	
//  up	
		while((pos!=0)&&heap[pos].priority>heap[parent(pos)].priority) {
		swap(pos,parent(pos)); 
		helpMap(pos);
		pos = parent(pos);
	}
	helpMap(pos);
	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -