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 fi first
#define se second
#define ll long long
#define pii pair<int, int>
using namespace std;
const int N = (1 << 18);
const int INF = 1e9;
int n, q;
vector<pii> gr[3 * N];
void build (int l = 1, int r = N, int v = 1) {
if (l == r) {
gr[l].push_back({v + N, 0});
return;
}
int mid = (l + r) >> 1;
build(l, mid, v << 1);
build(mid + 1, r, v << 1 ^ 1);
gr[(v << 1) + N].push_back({v + N, 0});
gr[((v << 1) ^ 1) + N].push_back({v + N, 0});
}
void add_road (int l1, int r1, int x, int v = 1, int l = 1, int r = N) {
if (l > r1 || r < l1)
return;
if (l1 <= l && r <= r1) {
gr[v + N].push_back({x, 1});
return;
}
int mid = (l + r) >> 1;
add_road (l1, r1, x, v << 1, l, mid);
add_road (l1, r1, x, v << 1 ^ 1, mid + 1, r);
}
vector<int> deikstra (vector<pii> v) {
vector<int> dist(3 * N, INF);
for (auto i : v)
dist[i.fi] = i.se;
set<pii> st;
for (auto i = 1; i < 3 * N; ++i)
st.insert({dist[i], i});
while (st.size()) {
auto p = *st.begin();
st.erase(st.begin());
for (auto i : gr[p.se])
if (dist[i.fi] > p.fi + i.se) {
st.erase({dist[i.fi], i.fi});
dist[i.fi] = p.fi + i.se;
st.insert({dist[i.fi], i.fi});
}
}
vector<int> now(n + 1);
for (int i = 1; i <= n; ++i)
now[i] = dist[i];
return now;
}
signed main () {
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
build();
cin >> n;
for (int i = 1; i <= n; ++i) {
int l, r;
cin >> l >> r;
add_road (l, r, i);
}
vector<int> dist_from_n = deikstra({{n, 0}});
vector<int> dist_from_one = deikstra({{1, 0}});
vector<pii> v;
for (int i = 1; i <= n; ++i)
v.push_back({i, dist_from_n[i] + dist_from_one[i] - (1 < i && i < n)});
vector<int> ans = deikstra(v);
cin >> q;
while (q--) {
int x;
cin >> x;
if (ans[x] == INF)
cout << "-1\n";
else
cout << ans[x] << '\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... |