Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <cstdio>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- #include <bits/stdc++.h>
- using namespace std;
- class Heap
- {
- public:
- vector<int> v;
- int heapsize;
- Heap()
- {
- v.push_back(INT_MAX);
- heapsize = 0;
- }
- int parent(int i)
- {
- return floor(i/2);
- }
- int left(int i)
- {
- return 2*i;
- }
- int right(int i)
- {
- return 2*i+1;
- }
- void buildMinHeap();
- void minHeapify(int i);
- void increaseKey(int i,int value);
- void insertKey(int value);
- int findIndex(int i,int value);
- int extractMin();
- bool isEmpty();
- int _min(){return v[1];}
- void _clear(){v.clear(); v.push_back(INT_MAX);heapsize = 0;}
- };
- void Heap::buildMinHeap()
- {
- for(int i = heapsize/2; i >= 1; i--)
- {
- minHeapify(i);
- }
- }
- void Heap::minHeapify(int i)
- {
- int l = left(i);
- int r = right(i);
- int smallest;
- if(l <= heapsize && v[l] < v[i])
- {
- smallest = l;
- }
- else
- {
- smallest = i;
- }
- if(r <= heapsize && v[r] < v[smallest])
- {
- smallest = r;
- }
- if(smallest != i)
- {
- swap(v[smallest],v[i]);
- minHeapify(smallest);
- }
- }
- void Heap::increaseKey(int i, int value)
- {
- v[i] = value;
- while(i > 1 && v[parent(i)] > v[i])
- {
- swap(v[parent(i)],v[i]);
- i = parent(i);
- }
- }
- void Heap::insertKey(int value)
- {
- v.push_back(INT_MAX);
- heapsize++;
- increaseKey(heapsize,value);
- }
- int Heap::extractMin()
- {
- if(heapsize < 1)
- return -1;
- int _min = v[1];
- v[1] = v[heapsize];
- heapsize--;
- minHeapify(1);
- return _min;
- }
- int Heap::findIndex(int i, int value)
- {
- int tmpindex;
- // cout << i << " " << heapsize << endl;
- if(v[i] == value)
- return i;
- else if(2*i > heapsize)
- return -1;
- else if((tmpindex = findIndex(2*i,value)) > 0)
- {
- return tmpindex;
- }
- else if(2*i+1 > heapsize)
- {
- return -1;
- }
- else
- {
- return findIndex(2*i+1,value);
- }
- return -1;
- }
- bool Heap::isEmpty()
- {
- if(heapsize == 0)
- return true;
- return false;
- }
- int main() {
- Heap h;
- h.insertKey(3);
- // cout << h.heapsize << endl;
- h.insertKey(2);
- h.insertKey(1);
- while(!h.isEmpty())
- {
- cout << h.extractMin() << " ";
- }
- cout << endl;
- /* Enter your code here. Read input from STDIN. Print output to STDOUT */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement