-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeap.cpp
66 lines (61 loc) · 1.38 KB
/
Heap.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* Heap.cpp
*
* Created on: Jul 24, 2016
* Author: Mohamed
*/
#include<bits/stdc++.h>
using namespace std;
class HeapBuilder {
private:
vector<int> data_;
vector<pair<int, int> > swaps_;
int n;
void WriteResponse() const {
cout << swaps_.size() << "\n";
for (int i = 0; i < swaps_.size(); ++i) {
cout << swaps_[i].first << " " << swaps_[i].second << "\n";
}
}
void ReadData() {
cin >> n;
data_.resize(n);
for (int i = 0; i < n; ++i)
cin >> data_[i];
}
void sift_down(int i) {
int minimum = i;
int l = 2 * i + 1;
int r = l + 1;
if (l < n && data_[l] < data_[minimum]) {
minimum = l;
}
if (r < n && data_[r] < data_[minimum]) {
minimum = r;
}
if(minimum!=i){
swap(data_[i],data_[minimum]);
swaps_.push_back(make_pair(i, minimum));
sift_down(minimum);
}
}
void GenerateSwaps() {
swaps_.clear();
// The following naive implementation just sorts
// the given sequence using selection sort algorithm
// and saves the resulting sequence of swaps.
// This turns the given array into a heap,
// but in the worst case gives a quadratic number of swaps.
//
// TODO: replace by a more efficient implementation
for (int i = (n / 2) - 1; i >= 0; --i) {
sift_down(i);
}
}
public:
void Solve() {
ReadData();
GenerateSwaps();
WriteResponse();
}
};