This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx,popcnt,sse4,abm")
#include <bits/stdc++.h>
using namespace std;
#ifdef WAIMAI
#define debug(HEHE...) cout << "[" << #HEHE << "] : ", dout(HEHE)
void dout() {cout << '\n';}
template<typename T, typename...U>
void dout(T t, U...u) {cout << t << (sizeof...(u) ? ", " : ""), dout(u...);}
#else
#define debug(...) 7122
#endif
#define ll long long
#define Waimai ios::sync_with_stdio(false), cin.tie(0)
#define FOR(x,a,b) for (int x = a, I = b; x <= I; x++)
#define pb emplace_back
#define F first
#define S second
#define lpos pos*2
#define rpos pos*2+1
const int INF = 1e9;
const int SIZE = 2e5 + 5;
const int TSIZ = SIZE << 1;
int n, m, sz;
vector<pair<int, int>> adj[TSIZ];
int id[SIZE << 2], dis1[TSIZ], disn[TSIZ], dp[TSIZ];
void build(int pos, int l, int r) {
id[pos] = (l == r ? l : ++sz);
if (pos > 1) adj[id[pos]].pb(id[pos >> 1], 0);
if (l < r) {
int mid = (l + r) / 2;
build(lpos, l, mid);
build(rpos, mid + 1, r);
}
}
void add(int pos, int l, int r, int L, int R, int i) {
if (l == L && r == R) {
adj[id[pos]].pb(i, 1);
return;
}
int mid = (L + R) / 2;
if (r <= mid) add(lpos, l, r, L, mid, i);
else if (l > mid) add(rpos, l, r, mid + 1, R, i);
else {
add(lpos, l, mid, L, mid, i);
add(rpos, mid + 1, r, mid + 1, R, i);
}
}
void cal_dis(int s, int *dis) {
fill(dis + 1, dis + sz + 1, INF);
deque<int> q;
dis[s] = 0, q.pb(s);
while (q.size()) {
int pos = q.front();
q.pop_front();
for (auto [np, w] : adj[pos]) if (dis[pos] + w < dis[np]) {
dis[np] = dis[pos] + w;
if (w == 0) q.emplace_front(np);
else q.pb(np);
}
}
}
void solve() {
cin >> n;
sz = n, build(1, 1, n);
FOR (i, 1, n) {
int l, r;
cin >> l >> r;
add(1, l, r, 1, n, i);
}
cal_dis(1, dis1);
cal_dis(n, disn);
fill(dp + 1, dp + sz + 1, INF);
FOR (i, 1, n) dp[i] = dis1[i] + disn[i] - (i != 1 && i != n);
iota(id + 1, id + n + 1, 1);
sort(id + 1, id + n + 1, [&](int l, int r) {
return dp[l] < dp[r];
});
deque<int> q;
FOR (i, 1, n) q.pb(id[i]);
while (q.size()) {
int pos = q.front();
q.pop_front();
for (auto [np, w] : adj[pos]) if (dp[pos] + w < dp[np]) {
dp[np] = dp[pos] + w;
if (w == 0) q.emplace_front(np);
else q.pb(np);
}
}
cin >> m;
while (m--) {
int i;
cin >> i;
cout << (dp[i] >= INF ? -1 : dp[i]) << '\n';
}
}
int main() {
Waimai;
solve();
}
# | 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... |