-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsolution.cpp
128 lines (105 loc) · 2.62 KB
/
solution.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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <unordered_map>
using namespace std;
const int MAX_VAL = 1000000 + 1;
// n -> number of data streams
// initialize -> O(n * log n)
// each query -> O(log n * log n)
class orderStatsTree{
vector<unsigned int> BIT;
public:
int size;
orderStatsTree(){
this->BIT = vector<unsigned int>(MAX_VAL, 0);
this->size = 0;
}
void insert(int val);
void remove(int val);
int find(int k);
void update(int index, int add);
int sum(int index);
};
void orderStatsTree::update(int index, int add){
while (index > 0 && index < this->BIT.size()){
this->BIT[index] += add;
index = index + (index & (-index));
}
}
void orderStatsTree::insert(int val){
update(val, 1);
this->size++;
}
void orderStatsTree::remove(int val){
update(val, -1);
this->size--;
}
int orderStatsTree::find(int k){
int l = 0;
int h = BIT.size();
// search for the kth biggest element
k = this->size - k + 1;
while (l < h){
int mid = (l + h) / 2;
if (k <= sum(mid))
h = mid;
else
l = mid+1;
}
return l;
}
int orderStatsTree::sum(int index){
int sum = 0;
while (index > 0){
sum += this->BIT[index];
index = index - (index & (-index));
}
return sum;
}
int main(){
int n, k, q;
cin >> n >> k >> q;
vector<queue<int>> streams(n);
orderStatsTree* tree = new orderStatsTree();
unordered_map<int, priority_queue<int, vector<int>, greater<int>>> data_to_stream;
for (int a = 0; a < n; a++){
int stream_size;
cin >> stream_size;
for (int b = 0; b < stream_size; b++){
int val;
cin >> val;
streams[a].push(val);
}
}
for (int a=0; a<n; a++){
int val = streams[a].front();
streams[a].pop();
tree->insert(val);
data_to_stream[val].push(a);
}
for (int a = 0; a < q; a++) {
int router;
cin >> router;
if (tree->size == 0) {
cout << -1 << "\n";
continue;
}
if (router > tree->size) {
router = tree->size;
}
int res = tree->find(router);
tree->remove(res);
int stream = data_to_stream[res].top();
data_to_stream[res].pop();
if (!streams[stream].empty()) {
int val = streams[stream].front();
streams[stream].pop();
tree->insert(val);
data_to_stream[val].push(stream);
}
cout << res << "\n";
}
return 0;
}