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 pll pair<ll, ll>
using namespace std;
const ll N = (1 << 18);
const ll INF = 1e18;
ll n, q;
vector<pll> gr[3 * N + 10];
void build (ll l = 1, ll r = N, ll v = 1) {
if (l == r) {
gr[l].push_back({v + N, 0});
return;
}
ll 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 (ll l1, ll r1, ll x, ll v = 1, ll l = 1, ll r = N) {
if (l > r1 || r < l1)
return;
if (l1 <= l && r <= r1) {
gr[v + N].push_back({x, 1});
return;
}
ll 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<ll> deikstra (vector<pll> v) {
vector<ll> dist(3 * N, INF);
for (auto i : v)
dist[i.fi] = i.se;
set<pll> st;
for (auto i = 0; 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<ll> now(n + 1);
for (ll 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 (ll i = 1; i <= n; ++i) {
ll l, r;
cin >> l >> r;
add_road (l, r, i);
}
vector<ll> dist_from_n = deikstra({{n, 0}});
vector<ll> dist_from_one = deikstra({{1, 0}});
vector<pll> v;
for (ll i = 1; i <= n; ++i)
v.push_back({i, dist_from_n[i] + dist_from_one[i] - (1 < i && i < n)});
vector<ll> ans = deikstra(v);
cin >> q;
while (q--) {
ll 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... |