This repository has been archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTop_K_Query.cpp
53 lines (53 loc) · 1.47 KB
/
Top_K_Query.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
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
class TopKDataStructure {
private:
int k;
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
public:
TopKDataStructure(int k) : k(k) {}
void addElement(int element) {
if (minHeap.size() < k) {
minHeap.push(element);
} else if (element > minHeap.top()) {
minHeap.pop();
minHeap.push(element);
}
}
std::vector<int> getTopK() {
std::vector<int> result;
result.reserve(minHeap.size());
while (!minHeap.empty()) {
result.push_back(minHeap.top());
minHeap.pop();
}
std::reverse(result.begin(), result.end());
for (int element : result) {
minHeap.push(element);
}
return result;
}
};
int main() {
int k;
std::cout << "Enter the value of k for Top-k queries: ";
std::cin >> k;
TopKDataStructure topKDS(k);
int numElements;
std::cout << "Enter the number of elements to add: ";
std::cin >> numElements;
std::cout << "Enter the elements:" << std::endl;
for (int i = 0; i < numElements; ++i) {
int element;
std::cin >> element;
topKDS.addElement(element);
}
std::vector<int> topKElements = topKDS.getTopK();
std::cout << "Top-" << k << " elements:" << std::endl;
for (int element : topKElements) {
std::cout << element << " ";
}
return 0;
}