/* Author : Mychecksdead */
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MOD (1000000000+7)
#define MOD1 (998244353)
#define pb push_back
#define all(x) x.begin(), x.end()
#define en cout << '\n'
#define ff first
#define ss second
#define pii pair<int,int>
#define vi vector<int>
const int N = 5000+100, M = 1e5+10, K = 22, MX = 30;
int n, L[N], R[N], q, DP[N][N], rmq[N][K][2];
int get(int l, int r){
int k = int(log2(r-l+1));
return R[rmq[k][k][0]] > R[rmq[r-(1<<k)+1][k][0]] ? rmq[l][k][0] : rmq[r-(1<<k)+1][k][0];
}
int get2(int l, int r){
int k = int(log2(r-l+1));
return L[rmq[k][k][1]] < L[rmq[r-(1<<k)+1][k][1]] ? rmq[l][k][1] : rmq[r-(1<<k)+1][k][1];
}
void solve(){
cin >> n;
vector<pii> v;
for(int i = 1; i <= n; ++i){
cin >> L[i] >> R[i];
rmq[i][0][0] = i;
rmq[i][0][1] = i;
}
for(int j = 1; j < K; ++j){
for(int i = 1; i + (1<<j) <= n+1; ++i){
rmq[i][j][0] = R[rmq[i][j-1][0]] > R[rmq[i+(1<<(j-1))][j-1][0]] ? rmq[i][j-1][0] : rmq[i+(1<<(j-1))][j-1][0];
rmq[i][j][1] = L[rmq[i][j-1][1]] < L[rmq[i+(1<<(j-1))][j-1][1]] ? rmq[i][j-1][1] : rmq[i+(1<<(j-1))][j-1][1];
}
}
vi go(n + 1);
for(int i = 1; i <= n; ++i){
go[i] = 0;
int r = R[i];
bool bad = 0;
while(r < n){
if(r == R[get(L[i], r)]){
bad = 1;
break;
}
r = R[get(L[i], r)];
go[i]++;
}
int l = L[i];
while(l > 1){
if(l == L[get2(l, R[i])]){
bad = 1;
break;
}
l = L[get2(l, R[i])];
go[i]++;
}
if(bad) go[i] = MOD;
// cout << go[i] << ' ';
}
// en;
cin >> q;
for(int i = 1; i <= q; ++i){
int v; cin >> v;
vi dist(n + 1, MOD);
dist[v] = 0;
set<int> A;
for(int j = 1; j <= n; ++j){
if(j != v)
A.insert(j);
}
queue<int> Q;
Q.push(v);
vector<bool> vis(n + 1);
while(!Q.empty()){
int u = Q.front(); Q.pop();
auto it = A.lower_bound(get(L[u], R[u]));
if(it != A.end() && (*it) == get(L[u], R[u])){
dist[*it] = dist[u] + 1;
Q.push(*it);
A.erase(it);
}
it = A.lower_bound(get2(L[u], R[u]));
if(it != A.end() && (*it) == get2(L[u], R[u])){
dist[*it] = dist[u] + 1;
Q.push(*it);
A.erase(it);
}
}
// for(int j = 1 ; j <= n; ++j) cout << dist[j] << ' ';
int tot = MOD;
for(int j = 1; j <= n; ++j) tot = min(tot, go[j] + dist[j]);
cout << (tot>=MOD ? -1 : tot + 1) << '\n';
}
}
int main(){
cin.tie(0); ios::sync_with_stdio(0);
int tt = 1, aa;
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
while(tt--){
solve();
en;
}
cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" seconds\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... |