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;
#define int long long
const int INF = 1e15;
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<vector<int>> adj(n+1);
vector<pair<int,int>> ranges(n+1);
for(int i=1;i<=n;i++){
int l,r;cin>>l>>r;
ranges[i]={l,r};
for(int j=l;j<=r;j++)adj[j].emplace_back(i);
}
vector<int> distL(n+1,INF);
vector<int> distR(n+1,INF);
{
// distL calculation
queue<pair<int,int>> q;
for(int i=1;i<=n;i++){
if(ranges[i].first==1)q.emplace(i,0);
}
vector<bool> visited(n+1);
while(!q.empty()){
auto [idx,dist] = q.front();q.pop();
if(visited[idx])continue;
visited[idx]=true;
distL[idx]=dist;
for(int&i:adj[idx])if(!visited[i])q.emplace(i,dist+1);
}
}
{
// distR calculation
queue<pair<int,int>> q;
for(int i=1;i<=n;i++){
if(ranges[i].second==n)q.emplace(i,0);
}
vector<bool> visited(n+1);
while(!q.empty()){
auto [idx,dist] = q.front();q.pop();
if(visited[idx])continue;
visited[idx]=true;
distR[idx]=dist;
for(int&i:adj[idx])if(!visited[i])q.emplace(i,dist+1);
}
}
vector<int> totdist(n+1,INF);
{
// totdist calculation
vector<bool> visited(n+1);
priority_queue<pair<int,int>> q;
for(int i=1;i<=n;i++){
q.emplace(-(distL[i]+distR[i]+1),i);
}
while(!q.empty()){
auto [dist,idx] = q.top();q.pop();dist=-dist;
if(visited[idx])continue;
visited[idx]=true;
totdist[idx]=dist;
for(int&i:adj[idx])if(!visited[i])q.emplace(-dist-1,i);
}
}
int q;
cin >> q;
for(int i=1;i<=q;i++){
int x;cin>>x;
if(totdist[x]>=INF)cout<<"-1\n";
else cout << totdist[x] << '\n';
}
}
# | 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... |