-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path116_kth_largest_element_in_stream.cpp
More file actions
115 lines (95 loc) · 2.02 KB
/
Copy path116_kth_largest_element_in_stream.cpp
File metadata and controls
115 lines (95 loc) · 2.02 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// https://practice.geeksforgeeks.org/problems/kth-largest-element-in-a-stream/0
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<int>v, int size)
{
for (int i = 0; i < size; ++i)
{
cout << v[i] << " ";
}
cout << endl;
}
void minheapify_up(vector<int> &minheap, int size, int ind)
{
if (ind < 0)
return;
int left = 2 * ind + 1;
int right = left + 1;
int smallest = ind;
if (left < size && minheap[left] < minheap[smallest])
smallest = left;
if (right < size && minheap[right] < minheap[smallest])
smallest = right;
if (smallest != ind)
{
int t = minheap[ind];
minheap[ind] = minheap[smallest];
minheap[smallest] = t;
}
minheapify_up(minheap, size, (ind + 1) / 2 - 1);
}
void minheapify_down(vector<int> &minheap, int size, int ind)
{
int left = 2 * ind + 1;
int right = left + 1;
int smallest = ind;
if (left < size && minheap[left] < minheap[smallest])
smallest = left;
if (right < size && minheap[right] < minheap[smallest])
smallest = right;
if (smallest != ind)
{
int t = minheap[ind];
minheap[ind] = minheap[smallest];
minheap[smallest] = t;
minheapify_down(minheap, size, smallest);
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--)
{
int k, n;
cin >> k >> n;
vector<int> minheap(k);
int size = 0;
for (int i = 0; i < k; ++i)
{
int temp;
cin >> temp;
minheap[size] = temp;
size++;
minheapify_up(minheap, size, size - 1);
if (i < k - 1)
cout << -1 << " ";
else
cout << minheap[0] << " ";
}
// cout << "\nminheap:";
// print_vector(minheap, size);
for (int i = k; i < n; ++i)
{
int temp;
cin >> temp;
// cur ele belongs to k-largest elements
if (minheap[0] < temp)
{
minheap[0] = temp;
minheapify_down(minheap, size, 0);
}
// cout << "\nminheap:";
// print_vector(minheap, size);
cout << minheap[0] << " ";
}
cout << endl;
}
return 0;
}