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>
using namespace std;
mt19937 rnd(51);
#define ll long long
#define pb push_back
#define ld long double
const int INF = 1e9;
struct SparseTable {
int n;
vector<vector<int>> po_min, po_max;
vector<int> lg;
SparseTable(vector<int> a) {
n = a.size();
lg.resize(n + 1);
po_min.resize(20);
po_max.resize(20);
for (int i = 0; i < 20; i++) {
po_min[i].resize(n);
po_max[i].resize(n);
if ((1 << i) <= n) {
lg[1 << i] = i;
}
}
for (int i = 1; i <= n; i++) {
lg[i] = max(lg[i], lg[i - 1]);
}
for (int i = 0; i < n; i++) {
po_min[0][i] = po_max[0][i] = a[i];
}
for (int i = 1; i < 20; i++) {
for (int j = 0; j + (1 << i) <= n; j++) {
po_min[i][j] = min(po_min[i - 1][j], po_min[i - 1][j + (1 << (i - 1))]);
po_max[i][j] = max(po_max[i - 1][j], po_max[i - 1][j + (1 << (i - 1))]);
}
}
}
int get_min(int l, int r) {
int d = lg[r - l + 1];
return min(po_min[d][l], po_min[d][r - (1 << d) + 1]);
}
int get_max(int l, int r) {
int d = lg[r - l + 1];
return max(po_max[d][l], po_max[d][r - (1 << d) + 1]);
}
};
signed main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
#endif // LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, k, m;
cin >> n >> k >> m;
vector<int> a(m), b(m);
vector<vector<int>> add_l(n + 1), add_r(n + 1), del_l(n + 1), del_r(n + 1);
for (int i = 0; i < m; i++) {
cin >> a[i] >> b[i];
a[i]--, b[i]--;
if (a[i] < b[i]) {
add_r[a[i]].pb(b[i]);
del_r[min(b[i], a[i] + k)].pb(b[i]);
} else {
add_l[max(b[i], a[i] - k + 1)].pb(b[i]);
del_l[a[i] + 1].pb(b[i]);
}
}
multiset<int> st_r{-INF}, st_l{INF};
vector<int> up_l(n), up_r(n);
for (int i = 0; i < n; i++) {
for (auto to : add_r[i]) {
st_r.insert(to);
}
for (auto to : del_r[i]) {
st_r.erase(st_r.find(to));
}
up_r[i] = *st_r.rbegin();
for (auto to : add_l[i]) {
st_l.insert(to);
}
for (auto to : del_l[i]) {
st_l.erase(st_l.find(to));
}
up_l[i] = *st_l.begin();
}
SparseTable L(up_l), R(up_r);
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int s, t;
cin >> s >> t;
s--, t--;
pair<int,int> seg{s, s};
int ans = 0;
while (!(seg.first <= t && t <= seg.second)) {
pair<int,int> new_seg{min(seg.first, L.get_min(seg.first, seg.second)), max(seg.second, R.get_max(seg.first, seg.second))};
if (seg == new_seg) {
ans = -1;
break;
}
seg = new_seg;
ans++;
}
cout << ans << endl;
}
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... |