#include<bits/stdc++.h>
using namespace std;
#define inf (int)2e9
#define _ <<' '<<
#define nl '\n'
void solve(){
int n, k, m;
cin>>n>>k>>m;
vector<int> in[n], out[n];
for(int i = 0; i < m; i++){
int a, b;
cin>>a>>b;
a--, b--;
in[a].push_back(b);
out[a < b ? min(b-1, a+k-1) : max(b+1, a-k+1)].push_back(b);
}
multiset<int> st;
int l[n][18], r[n][18];
for(int i = 0; i < n; i++){
for(int b : in[i]){
if(i < b) st.insert(b);
}
r[i][0] = (st.empty() ? i : *st.rbegin());
for(int b : out[i]){
if(i < b) st.erase(st.find(b));
}
}
st.clear();
for(int i = n-1; i >= 0; i--){
for(int b : in[i]){
if(i > b) st.insert(b);
}
l[i][0] = (st.empty() ? i : *st.begin());
for(int b : out[i]){
if(i > b) st.erase(st.find(b));
}
}
int lg[n+1];
for(int i = 1, p = 1, c = 0; i <= n; i++){
if(p * 2 <= i) p *= 2, c++;
lg[i] = c;
}
int ml[n][18][18], mr[n][18][18];
auto qry = [&](int w, int j, int l, int r){
int c = lg[r-l+1];
if(!w) return min(ml[l][j][c], ml[r - (1<<c) + 1][j][c]);
return max(mr[l][j][c], mr[r - (1<<c) + 1][j][c]);
};
for(int j = 0; j < 18; j++){
for(int i = 0; i < n; i++){
if(!j) continue;
l[i][j] = qry(0, j-1, l[i][j-1], r[i][j-1]);
r[i][j] = qry(1, j-1, l[i][j-1], r[i][j-1]);
}
for(int k = 0; k < 18; k++){
for(int i = 0; i + (1<<k) - 1 < n; i++){
if(k == 0){
ml[i][j][k] = l[i][j];
mr[i][j][k] = r[i][j];
continue;
}
ml[i][j][k] = min(ml[i][j][k-1], ml[i + (1<<k-1)][j][k-1]);
mr[i][j][k] = max(mr[i][j][k-1], mr[i + (1<<k-1)][j][k-1]);
}
}
}
int q;
cin>>q;
while(q--){
int a, b;
cin>>a>>b;
a--, b--;
int cl = a, cr = a, ans = 1;
for(int j = 17; j >= 0; j--){
int ncl = qry(0, j, cl, cr);
int ncr = qry(1, j, cl, cr);
if(ncl <= b and b <= ncr) continue;
cl = ncl;
cr = ncr;
ans += 1<<j;
}
cout<<(ans > m ? -1 : ans)<<nl;
}
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(NULL);cout.tie(NULL);
int t = 1;
//cin>>t;
while(t--) solve();
return 0;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |