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 iter(a) a.begin(), a.end()
#define lsort(a) sort(iter(a))
#define gsort(a) sort(iter(a), greater<>())
#define eb emplace_back
#define pob pop_back()
#define ef emplace_front
#define pof pop_front()
#define mp make_pair
#define F first
#define S second
#define uni(a) a.resize(unique(iter(a)) - a.begin())
#define printv(a, b) { \
for(auto pv : a) b << pv << " "; \
b << "\n"; \
}
using namespace std;
typedef long long ll;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
struct SparseTable{
vector<vector<pii>> st;
int n;
SparseTable(vector<pii>& a){
n = a.size();
st.resize(20, vector<pii>(n));
st[0] = a;
for(int i = 1; i < 20; i++){
for(int j = 0; j + (1 << i) - 1 < n; j++){
st[i][j] = min(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);
}
}
}
pii query(int l, int r){
int lg = __lg(r - l + 1);
return min(st[lg][l], st[lg][r - (1 << lg) + 1]);
}
};
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
int n, q;
cin >> n >> q;
vector<int> l(n + 1), r(n + 1);
vector<vector<int>> anc(20, vector<int>(n + 1));
for(int i = 1; i <= n; i++){
cin >> l[i] >> r[i];
}
vector<int> dr = r;
lsort(dr);
uni(dr);
int sz = dr.size();
vector<pii> mn(sz, mp(INT_MAX, -1));
for(int i = 1; i <= n; i++){
int pos = lower_bound(iter(dr), r[i]) - dr.begin();
mn[pos] = min(mn[pos], mp(l[i], i));
}
SparseTable st(mn);
for(int i = 1; i <= n; i++){
int lp = lower_bound(iter(dr), l[i]) - dr.begin();
int rp = lower_bound(iter(dr), r[i]) - dr.begin();
anc[0][i] = st.query(lp, rp).S;
if(anc[0][i] == i) anc[0][i] = -1;
}
for(int i = 1; i < 20; i++){
for(int j = 1; j <= n; j++){
if(anc[i - 1][j] == -1) anc[i][j] = -1;
else anc[i][j] = anc[i - 1][anc[i - 1][j]];
}
}
while(q--){
int s, e;
cin >> s >> e;
if(s == e){
cout << "0\n";
continue;
}
if(r[s] > r[e]){
cout << "impossible\n";
continue;
}
int ans = 0;
int now = e;
for(int i = 19; i >= 0; i--){
if(anc[i][now] == -1) continue;
if(l[anc[i][now]] <= r[s]) continue;
now = anc[i][now];
ans += 1 << i;
}
if(r[s] < l[now] && anc[0][now] != -1) ans++, now = anc[0][now];
if(r[s] < l[now]) cout << "impossible\n";
else cout << ans + 1 << "\n";
}
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... |