#include <bits/stdc++.h>
#define F first
#define S second
using namespace std;
const int N = 1e5 + 10;
const int LOG = 17;
int n, l[N], r[N], up[N][LOG], logs[N];
pair<int,int> st[N][LOG];
bool cmp(int i, int j) {
if(r[i] == r[j]) return l[i] < l[j];
return r[i] < r[j];
}
pair<int,int> Query(int l, int r) {
int j = logs[r - l + 1];
return min(st[l][j], st[r - (1 << j) + 1][j]);
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int q;
cin >> n >> q;
for(int i = 2; i <= n; i++) logs[i] = logs[i >> 1] + 1;
for(int i = 1; i <= n; i++) cin >> l[i] >> r[i];
vector<int> order(n + 1), p(n + 1);
for(int i = 1; i <= n; i++) order[i] = i;
for(int i = 1; i <= n; i++) p[order[i]] = i;
sort(order.begin() + 1, order.end(), cmp);
//for(int i = 1; i <= n; i++) cout << l[order[i]] << " " << r[order[i]] << endl;
vector<int> L(n + 1), R(n + 1);
for(int i = 1; i <= n; i++) {
L[i] = l[order[i]];
R[i] = r[order[i]];
}
for(int i = 1; i <= n; i++) st[i][0] = {L[i], i};
for(int j = 1; j < LOG; j++) {
for(int i = 1; i + (1 << (j - 1)) <= n; i++) {
st[i][j] = min(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
}
}
vector<int> prv(n + 1);
for(int i = 1; i <= n; i++) {
int tl = 1, tr = i, rez = i;
while(tl <= tr) {
int mid = tl + tr >> 1;
if(R[mid] >= L[i]) {
rez = mid;
tr = mid - 1;
} else {
tl = mid + 1;
}
}
prv[i] = rez;
up[i][0] = rez;
}
for(int j = 1; j < LOG; j++) {
for(int i = 1; i <= n; i++) {
up[i][j] = up[Query(up[i][j - 1], i).S][j - 1];
}
}
while(q--) {
int x, y;
cin >> x >> y;
x = p[x]; y = p[y];
if(x == y) {
cout << "0\n";
continue;
}
if(x > y) {
cout << "impossible\n";
continue;
}
if (l[y] <= r[x] && r[x] <= r[y]) {
cout << "1\n";
continue;
}
int res = 1;
for(int j = LOG - 1; j >= 0; j--) {
if(up[y][j] > x) {
res += (1 << j);
y = up[y][j];
}
}
if(up[y][0] > x) {
cout << "impossible\n";
} else {
cout << res << "\n";
}
}
}
# | 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... |