#include "robots.h"
#include <bits/stdc++.h>
#define pb push_back
#define fs first
#define sc second
using namespace std;
int a, b, t, k, tim;
vector<int> x, y, w, s, ordw, ords, vis;
bool check(){
tim++;
priority_queue<pair<int, int>> pq;
int p = 0;
for(int i = 0; i < a; i++){
while(p < t and w[ordw[p]] < x[i]){
int id = ordw[p++];
if(vis[id] != tim) pq.push({s[id], id});
}
for(int c = 0; c < k and pq.size(); c++){
int id = pq.top().sc;
pq.pop();
vis[id] = tim;
}
}
priority_queue<pair<int, int>> pq2;
p = 0;
for(int i = 0; i < b; i++){
while(p < t and s[ords[p]] < y[i]){
int id = ords[p];
p++;
if(vis[id] != tim) pq2.push({w[id], id});
}
for(int c = 0; c < k and pq2.size(); c++){
int id = pq2.top().sc;
pq2.pop();
vis[id] = tim;
}
}
for(int i = 0; i < t; i++){
if(vis[i] != tim) return 0;
}
return 1;
}
int putaway(int A, int B, int T, int X[], int Y[], int W[], int S[]) {
a = A, b = B, t = T;
for(int i = 0; i < a; i++) x.pb(X[i]);
for(int i = 0; i < b; i++) y.pb(Y[i]);
for(int i = 0; i < t; i++) w.pb(W[i]);
for(int i = 0; i < t; i++) s.pb(S[i]);
sort(x.begin(), x.end());
sort(y.begin(), y.end());
ordw.resize(t), ords.resize(t);
for(int i = 0; i < t; i++) ordw[i] = ords[i] = i;
sort(ordw.begin(), ordw.end(), [&](int i, int j){
if(w[i] != w[j]) return w[i] < w[j];
return i < j;
});
sort(ords.begin(), ords.end(), [&](int i, int j){
if(s[i] != s[j]) return s[i] < s[j];
return i < j;
});
int mxw = -1, mxs = -1;
if(a > 0) mxw = x.back();
if(b > 0) mxs = y.back();
for(int i = 0; i < t; i++){
if(!((a > 0 and w[i] < mxw) or (b > 0 and s[i] < mxs))) return -1;
}
for(int i = 0; i < t; i++) vis.pb(0);
tim = 0;
k = t;
if(!check()) return -1;
int l = 1, r = t;
while(l <= r){
int mid = (l + r) / 2;
k = mid;
if(check()) r = mid - 1;
else l = mid + 1;
}
return l;
}
// signed main(){
// int a[] = {6, 2, 9}, b[] = {4, 7}, c[] = {4,8,2,7,1,5,3,8,7,10}, d[] = {6,5,3,9,8,1,3,7,6,5};
// cout << putaway(3, 2, 10, a, b, c, d);
// }