import java.util.*;
import java.io.*;
// n k
// p_2 c_2
// ...
// p_n c_n
// x_1 y_1
// x_2 y_2
// ...
// x_k y_k
public class Main {
static List<List<Integer>> graph;
static int n;
static int[] min_dist_from_warp;
static int[] depth;
static boolean[] isPortal;
public static void bfs(int s) {
depth = new int[n+1];
Arrays.fill(depth, -1);
Queue<Integer> q = new ArrayDeque<>();
depth[s] = 0;
q.add(s);
while(!q.isEmpty()) {
int now = q.poll();
for (int next : graph.get(now)) {
if (depth[next] == -1) {
depth[next] = depth[now] + 1 ;
q.add(next);
}
}
}
}
public static int dfs(int now) {
int min_dist = 200001;
if(isPortal[now]) min_dist = 0;
for (int next : graph.get(now)) {
int from_child = dfs(next) + 1;
min_dist = Math.min(from_child, min_dist);
}
return min_dist_from_warp[now] = min_dist;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
graph = new ArrayList<>();
isPortal = new boolean[n+1];
for (int i=0; i<n+1; i++) {
graph.add(new ArrayList<>());
}
int[] parents = new int[n+1];
Arrays.fill(parents, -1);
for (int i=2; i<n+1; i++) {
st = new StringTokenizer(br.readLine());
int p = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
graph.get(p).add(i);
if (c==1) {
isPortal[i] = true;
}
}
bfs(1);
min_dist_from_warp = new int[n+1];
dfs(1);
StringBuilder sb = new StringBuilder();
for (int i=0; i<k; i++)
{
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
int dist_portal = min_dist_from_warp[x];
int dist_from_one = depth[y];
if (dist_portal == 200001 || dist_from_one == -1) {
sb.append(-1).append("\n");
} else {
sb.append(dist_portal+dist_from_one).append("\n");
}
}
System.out.println(sb);
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: