#include <bits/stdc++.h>
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define ll long long
using namespace std;
#define MAX_A 50000
#define MAX_B 50000
#define MAX_T 500000
static int X[MAX_A];
static int Y[MAX_B];
static int W[MAX_T];
static int S[MAX_T];
int A, B, T, i;
int res;
bool check(int rd,int n,int m,int k,int a[],int b[],pair <pair<int,int>,int> pw[],pair<pair<int,int>,int > ps[]){
// weight
int ind=0;
pair <int,int> g;
vector <int> fix(n+5,0);
vector <int> cnt(n+5,0);
int x;
priority_queue <pair<int,int> > p;
while (!p.empty()) p.pop();
ind=0;
for (int i=0; i<m; i++){
x=a[i];
while (ind<n && pw[ind].f.f<x){
p.push(mp(pw[ind].f.s,pw[ind].s));
ind++;
}
for (int i=0; i<rd; i++){
if (p.size()==0) break;
pair <int,int> g=p.top(); p.pop();
fix[g.s]=1;
}
}
while (!p.empty()) p.pop();
ind=0;
for (int i=0; i<k; i++){
x=a[i];
while (ind<n && ps[ind].f.f<x){
if (fix[ps[ind].s]==0)
p.push(mp(ps[ind].f.s,ps[ind].s));
ind++;
}
for (int i=0; i<rd; i++){
if (p.size()==0) break;
pair <int,int> g=p.top(); p.pop();
fix[g.s]=1;
}
}
for (int i=0; i<n; i++) if (fix[i]==0) return 0;
return 1;
}
int putaway(int m, int k, int n, int a[], int b[], int w[], int s[]) {
sort(a,a+m);
sort(b,b+k);
pair <pair <int,int> ,int> pw[n+5],ps[n+5];
pair <int,int> g;
for (int i=0; i<n; i++){
g=mp(w[i],s[i]);
pw[i]=mp(g,i);
g=mp(s[i],w[i]);
ps[i]=mp(g,i);
}
/*3 2 10
6 2 9
4 7
4 8 2 7 1 5 3 8 7 10
6 5 3 9 8 1 3 7 6 5*/
sort(pw,pw+n);
sort(ps,ps+n);
ll mx=n*max(m,k);
ll lg=log2(mx);
ll ans=0;
for (int i=lg; i>=0; i--){
if (check(ans+(1<<i),n,m,k,a,b,pw,ps)==0) ans+=(1<<i);
}
if (ans+1>mx) return -1;
return ans+1;
}
/*
int main() {
cin >> A >> B >> T;
int x[A+5],Y[B+5],W[T+5],S[T+5];
for (int i=0; i<A; i++) cin >> X[i];
for (int i=0; i<B; i++) cin >> Y[i];
for (int i=0; i<T; i++) cin >> W[i];
for (int i=0; i<T; i++) cin >> S[i];
/* FILE *f = fopen("robots.in", "r");
if (!f)
fail("Failed to open input file.");
res = fscanf(f, "%d", &A);
if (res != 1)
fail("Failed to read A from input file.");
if (A < 0 || A > MAX_A)
fail("A is out of bounds.");
res = fscanf(f, "%d", &B);
if (res != 1)
fail("Failed to read B from input file.");
if (B < 0 || B > MAX_B)
fail("B is out of bounds.");
res = fscanf(f, "%d", &T);
if (res != 1)
fail("Failed to read T from input file.");
if (T < 1 || T > MAX_T)
fail("T is out of bounds.");
for (i = 0; i < A; i++) {
res = fscanf(f, "%d", &X[i]);
if (res != 1)
fail("Failed to read data from input file.");
}
for (i = 0; i < B; i++) {
res = fscanf(f, "%d", &Y[i]);
if (res != 1)
fail("Failed to read data from input file.");
}
for (i = 0; i < T; i++) {
res = fscanf(f, "%d%d", &W[i], &S[i]);
if (res != 2)
fail("Failed to read data from input file.");
}
fclose(f);
int answer = putaway(A, B, T, X, Y, W, S);
printf("%d\n", answer);
return 0;
}*/