| # | Time | Username | Problem | Language | Result | Execution time | Memory | 
|---|---|---|---|---|---|---|---|
| 528566 | mhy908 | Railway Trip 2 (JOI22_ho_t4) | C++14 | 0 ms | 0 KiB | 
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define mp make_pair
#define eb emplace_back
#define F first
#define S second
#define all(x) x.begin(), x.end()
#define svec(x) sort(all(x))
#define press(x) x.erase(unique(all(x)), x.end());
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef pair<int, LL> pil;
typedef pair<LL, int> pli;
typedef pair<LL, LL> pll;
const int INF=1e9;
const LL LLINF=1e18;
int n, k, m, q, l[100010], r[100010];
multiset<int> ms;
vector<int> vcl[100010], vcr[100010];
struct SEG{
    pii tree[400010];
    pii func(pii a, pii b){return mp(min(a.F, b.F), max(a.S, b.S));}
    void upd(int point, int s, int e, int num, pii val){
        if(s==e){
            tree[point]=val;
            return;
        }
        if(num<=(s+e)/2)upd(point*2, s, (s+e)/2, num, val);
        else upd(point*2+1, (s+e)/2+1, e, num, val);
        tree[point]=func(tree[point*2], tree[point*2+1]);
    }
    pii query(int point, int s, int e, int a, int b){
        if(e<a||s>b)return mp(INF, 0);
        if(a<=s&&e<=b)return tree[point];
        return func(query(point*2, s, (s+e)/2, a, b), query(point*2+1, (s+e)/2+1, e, a, b));
    }
}seg[19];
int main(){
    scanf("%d %d %d", &n, &k, &m);
    for(int i=1; i<=m; i++){
        int a, b;
        scanf("%d %d", &a, &b);
        if(a<b)vcl[a].eb(b);
        else vcr[a].eb(b);
    }
    for(int i=1; i<=n; i++){
        for(auto j:vcl[i])ms.insert(j);
        r[i]=i;
        if(ms.size())r[i]=*ms.rbegin();
        if(i>=k){
            for(auto j:vcl[i-k+1])ms.erase(j);
        }
    }
    ms.clear();
    for(int i=n; i>=1; i--){
        for(auto j:vcr[i])ms.insert(j);
        l[i]=i;
        if(ms.size())l[i]=*ms.begin();
        if(i<=n-k+1){
            for(auto j:vcr[i+k-1])ms.erase(j);
        }
    }
    for(int i=1; i<=n; i++)seg[0].upd(1, 1, n, i, mp(l[i], r[i]));
    for(int i=1; i<=18; i++){
        for(int j=1; j<=n; j++){
            pii tmp=seg[i-1].query(1, 1, n, j, j);
            seg[i].upd(1, 1, n, j, seg[i-1].query(1, 1, n, tmp.F, tmp.S));
        }
    }
    scanf("%d", &q);
    for(int i=1; i<=q; i++){
        int a, b, ans=0;
        scanf("%d %d", &a, &b);
        pii r=mp(a, a);
        for(int j=18; j>=0; j--){
            pii r2=seg[j].query(1, 1, n, r.F, r.S);
            if(b<r2.F||b>r2.S)r=r2, ans+=(1<<j);
        }
        else if(ans>n)puts("-1");
        else printf("%d\n", ans+1);
    }
}
