-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhwheap2.cpp
More file actions
93 lines (75 loc) · 1.5 KB
/
hwheap2.cpp
File metadata and controls
93 lines (75 loc) · 1.5 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
#include <iostream>
#include <vector>
using namespace std;
struct Node
{
int val;
int index;
};
bool comprare(const Node &a, const Node &b)
{
return a.val < b.val;
}
void heap_shift_up(vector<Node> &heap, int i)
{
while (i > 0)
{
int p = (i - 1) / 2;
if (!(comprare(heap[p], heap[i])))
return;
swap(heap[p], heap[i]);
i = p;
}
}
void heap_shift_dwn(vector<Node> &heap, int i)
{
while (true)
{
int l = 2 * i + 1;
int r = 2 * i + 2;
int j = i;
if (l < heap.size() && comprare(heap[j], heap[l]))
j = l;
if (r < heap.size() && comprare(heap[j], heap[r]))
j = r;
if (j != i)
{
swap(heap[i], heap[j]);
i = j;
}
else
break;
}
}
void push_heap(vector<Node> &heap, Node v)
{
heap.push_back(v);
heap_shift_up(heap, heap.size() - 1);
}
void pop_heap(vector<Node> &heap)
{
heap[0] = heap.back();
heap.pop_back();
heap_shift_dwn(heap, 0);
}
int main()
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
int k;
cin >> k;
vector<Node> heap;
for (int i = 0; i < k; i++)
push_heap(heap, {a[i], i});
cout << heap[0].val << " ";
for (int i = k; i < n; i++)
{
push_heap(heap, {a[i], i});
while (!heap.empty() && heap[0].index <= i - k)
pop_heap(heap);
cout << heap[0].val;
}
}