哈希堆的实现
来源:互联网 发布:域名怎么和服务器绑定 编辑:程序博客网 时间:2024/06/16 17:03
hash堆额主要用途在于滑动窗口找最值
// 传入函数为myless 为 小堆 默认为小堆bool myless(int x, int y) { return x < y;}// 大堆bool mygreater(int x, int y) { return x > y;}// hash堆class HashHeap{private: vector<int> array; bool (*compatator)(int x, int y); unordered_map<int,int> hashmap; void heapUp(int i) { int x =array[i]; while (i > 0) { int p = (i - 1) / 2; if(!compatator(array[p],x)) { break; } array[i] = array[p]; hashmap[array[p]] = i; i = p; } array[i] = x; hashmap[x] = i; } void heapDown(int i) { int x = array[i]; while (2 * i + 1 < array.size()) { int min = 2 * i + 1; int max = 2 * i + 2; if(max < array.size() && compatator(array[max],array[min])) { min = max; } if(compatator(x,array[min])) { break; } array[i] = array[min]; hashmap[array[min]] = i; i = min; } array[i] = x; hashmap[x] = i; } void initial() { int end = (array.size() & 0x1) ? (array.size()) / 2 - 1: (array.size()-1) / 2; for (int i = end; i >= 0 ; --i) { heapDown(i); } for (int j = 0; j < array.size(); ++j) { hashmap.insert(make_pair(array[j],j)); } }public: HashHeap(vector<int>& another, bool (*compatator)(int x, int y) = myless) :array(another),compatator(compatator) { initial(); } void push(int x) { array.push_back(x); hashmap.insert(make_pair(x,array.size() -1)); heapUp(array.size() - 1); } int pop() { if(array.size() > 0) { int x = array[0]; swap(array[0],array[array.size() - 1]); hashmap.erase(x); array.pop_back(); heapDown(0); return x; } else{ return -1; } } void deleteElement(int key) { int idx = hashmap[key]; swap(array[array.size() - 1], array[idx]); for (unordered_map<int,int>::iterator it = hashmap.begin(); it != hashmap.end() ; ++it) { if(it->first == key) { hashmap.erase(it); break; } } hashmap[array[idx]] = idx; array.pop_back(); heapDown(idx); }};
阅读全文
0 0
- 哈希堆的实现
- 三子棋的实现的实现的实现
- JAVA实现的时钟实现
- 模态框的的实现
- 杀毒软件的简单实现的简单实现
- android的实现电话号码的实现
- 音频的实现音乐声音的实现
- malloc的实现、内存池的实现
- 异形窗体的实现
- 个性化的分页实现
- ASP数据库连接的实现
- Struts单选框的实现
- 梅西迭代算法的实现
- 翻页功能的实现
- Struts,MVC 的实现
- 实现JavaScript的继承
- 接口的显示实现
- TTerm的实现( 一)
- 学习httpbin源码记录(一)
- 程序员修炼之道:从小工到专家读书笔记
- [JLOI2013]卡牌游戏 (洛谷2059)
- 数据挖掘 —— 从入门到求职
- codeforces 587B Duff in Beach (dp)
- 哈希堆的实现
- storm学习(三)
- Leetcode---2.Add Two Numbers
- oracle 数据类型详解---日期型
- Project Euler__problem 3
- UVa 1596 Bug Hunt易错的地方
- 301 (div.2) E. Infinite Inversions
- Sublime Text 3运行JavaScript
- electron安装