C++ 加强堆

#include <iostream>
using namespace std;
#include <map>

class heap
{
public:
	int heapSize;
	int limit;
	int* heapArray;
	map<int, int> heapMap;
	heap(int limit)
	{
		this->limit = limit;
		this->heapArray = new int[limit];
		heapSize = 0;
	}
	void swapMap(int i, int j)
	{
		heapMap[heapArray[i]] = j;
		heapMap[heapArray[j]] = i;
	}
	void push(int value)
	{
		if (heapSize == limit)
		{
			cout << "heap is full";
			return;
		}
		heapArray[heapSize] = value;
		this->heapMap.insert(make_pair(value, heapSize));
		heapInsert(heapSize++);
	}
	void heapInsert(int index)
	{
		while (heapArray[index] > heapArray[(index - 1) / 2])
		{
			swapMap(index, (index - 1) / 2);
			swap(heapArray[index], heapArray[(index - 1) / 2]);
			
			index = (index - 1) / 2;
		}
	}
	void delete_num(int num)
	{
		int index = heapMap[num];
		swapMap(index, heapSize - 1);
		swap(heapArray[index], heapArray[heapSize-- - 1]);
		
		heapify(index);
		heapInsert(index);
	}
	int heapPop()
	{
		if (heapSize < 1)
		{
			cout << "heap is empty";
			return -1;
		}
		heapMap.erase(heapArray[0]);
		int temp = heapArray[0];
		swapMap(0, heapSize-1);
		swap(heapArray[0], heapArray[heapSize-- - 1]);
		heapify(0);
		return temp;
	}
	void heapify(int index)
	{
		int left= index * 2 + 1;
		while (left < heapSize)
		{
			int largest = left + 1 < heapSize && heapArray[left + 1] > heapArray[left] ? left + 1 : left;
			if (heapArray[index] > heapArray[largest])
				break;
			swapMap(index, largest);
			swap(heapArray[index], heapArray[largest]);
			
			index = largest;
			left= index * 2 + 1;
		}

	}
	void heapShow()
	{
		for (int i = 0; i < heapSize; i++)
		{
			cout << heapArray[i] << ' ';
		}
	}
};

函数名即为操作方式,也就不做注释了

利用反向索引表记录当前值所在位置,从表中获取当前的值,与末位值交换,进行heapify和heapInsert即可实现系统提供的堆无法实现的删除指定值操作

int main(void)
{
	heap a = heap(10);
	a.push(10);
	a.push(2);
	a.push(13);
	a.push(999);
	a.push(888);
	a.delete_num(999);
	int i = a.heapPop();
	cout << i << endl;
	a.heapShow();
	cout << a.heapSize;
	return 0;
}
输出:
888
13 2 10 3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值