Submission #574755

#TimeUsernameProblemLanguageResultExecution timeMemory
574755OttoTheDinoEvent Hopping (BOI22_events)C++17
100 / 100
313 ms41600 KiB
#include <bits/stdc++.h>
using namespace std;

#define rep(i,s,e)                  for (int i = s; i <= e; ++i)
#define rrep(i,s,e)                 for (int i = s; i >= e; --i)
#define pb                          push_back
#define pf                          push_front
#define fi                          first
#define se                          second
#define all(a)                      a.begin(), a.end()
#define len(a)                      (int)a.size()
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<ll> vll;

const int mx = 2e5, mx2 = 18;
int p[mx2+1][mx+1], sparse[mx2+1][mx+1], l[mx], r[mx];

int qry (int G, int H) {
    int P = __lg(H-G+1), a = sparse[P][G], b = sparse[P][H-(1<<P)+1];
    if (!a) return b;
    if (!b) return a;
    return (l[a]<l[b]?a:b);
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n, q; cin >> n >> q;

    set<int> st;
    rep (i,1,n) {
        cin >> l[i] >> r[i];
        st.insert(l[i]);
        st.insert(r[i]);
    }

    map<int,int> mp;
    int c = 1;
    for (int el : st) mp[el] = c++;

    rep (i,1,n) l[i] = mp[l[i]], r[i] = mp[r[i]];

    rep (i,1,n)
        if (!sparse[0][r[i]] || l[i] < l[sparse[0][r[i]]])
            sparse[0][r[i]] = i;

    rep (i,1,mx2) {
        rep (j,1,2*n-(1<<i)+1) {
            int x = j, y = j+(1<<(i-1));
            if (!sparse[i-1][x]) sparse[i][j] = sparse[i-1][y];
            else if (!sparse[i-1][y]) sparse[i][j] = sparse[i-1][x];
            else sparse[i][j] = (l[sparse[i-1][x]]<l[sparse[i-1][y]]?sparse[i-1][x]:sparse[i-1][y]);
        }
    }

    rep (i,1,n) p[0][i] = qry (l[i], r[i]);
    rep (i,1,mx2) rep (j,1,n) p[i][j] = p[i-1][p[i-1][j]];

    while (q--) {
        int s, e; cin >> s >> e;
        if (r[s]>r[e]) {
            cout << "impossible\n";
            continue;
        }
        if (s==e) {
            cout << "0\n";
            continue;
        }
        if (l[e]<=r[s]) {
            cout << "1\n";
            continue;
        }

        int cur = e, ans = 0;

        rrep (i,mx2,0) {
            if (l[p[i][cur]]>r[s]) {
                cur = p[i][cur];
                ans += 1<<i;
            }
        }

        if (l[p[0][cur]]<=r[s]) cout << ans+2 << "\n";
        else cout << "impossible\n";
    }

    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...