이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
const int M = 1e5+2;
int N = exp2(ceil(log2(M)));
struct rng {int l=INT_MAX, r, i;};
int nxt[M][30], L, R;
vector<rng> v;
rng seg[4*M];
rng comb(rng a, rng b) {
if (a.l < b.l) return a;
return b;
}
void update(int ind) {
while (ind /= 2) seg[ind] = comb(seg[ind*2], seg[ind*2+1]);
}
rng query(int l = 1, int r = N, int ind = 1) {
if (l > R || r < L) return {INT_MAX, 0, 0};
if (L <= l && r <= R) return seg[ind];
return comb(query(l, (l+r)/2, ind*2), query((l+r)/2+1, r, ind*2+1));
}
int lca(int p, int x) {
int l = 20, ans = 0;
while (v[p].l > x) {
while (l >= 0 && v[nxt[p][l]].l < x) l--;
if (l < 0) {
ans++;
break;
}
ans += (1<<l);
p = nxt[p][l];
} return ans;
}
signed main() {
cin.tie(0)->sync_with_stdio(0);
int n, q;
cin >> n >> q;
vector<int> rs;
vector<rng> cp; v.resize(n);
for (auto &[l, r, i]:v) cin >> l >> r;
for (int i = 0; i < n; i++) v[i].i = i;
cp = v;
sort(cp.begin(), cp.end(), [](rng a, rng b){return a.r < b.r;});
for (int i = 0; i < n; i++) {
rs.push_back(cp[i].r);
seg[i+N] = cp[i];
update(N+i);
}
for (auto [l, r, i]:v) {
nxt[i][0] = i;
L = lower_bound(rs.begin(), rs.end(), l)-rs.begin()+1;
R = upper_bound(rs.begin(), rs.end(), r)-rs.begin();
if (!R) continue;
auto tmp = query();
if (tmp.l < l) nxt[i][0] = tmp.i;
}
for (int i = 1; i <= 20; i++) {
for (int j = 0; j < n; j++) {
nxt[j][i] = nxt[nxt[j][i-1]][i-1];
}
}
while (q--) {
int a, b;
cin >> a >> b; a--; b--;
if (a == b) {
cout << 0 << endl;
continue;
}
if (v[b].r < v[a].r || v[a].r < v[nxt[b][20]].l) {
cout << "impossible" << endl;
} else {
cout << lca(b, v[a].r)+1 << endl;
}
}
return 0;
}
/*
8 5
1 2
3 4
1 5
6 7
5 10
10 20
15 20
999999999 1000000000
1 6
1 7
2 4
3 3
5 8
5 2
1 3
2 4
4 7
7 9
3 7
1 4
3 2
y = 5 \left\{1 < x < 3\right\}
y = 4 \left\{2 < x < 4\right\}
y = 3 \left\{4 < x < 7\right\}
y = 2 \left\{7 < x < 9\right\}
y = 1 \left\{3 < x < 7\right\}
*/
# | 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... |