Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Scanner;
- public class Friends {
- private ArrayList<int[]> values = new ArrayList<>();
- private Map<Integer, Integer> nodes;
- private Scanner in = new Scanner(System.in);
- private void getInput(){
- int n = in.nextInt();
- nodes = new HashMap<>(n);
- //Populate friends map
- for(int i = 0; i < n; i++){
- int n1 = in.nextInt();
- int n2 = in.nextInt();
- nodes.put(n1, n2);
- }
- //Test cases
- while(true){
- int n1 = in.nextInt();
- int n2 = in.nextInt();
- if(n1 == 0 && n2 == 0) break;
- values.add(new int[]{n1, n2});
- }
- }
- public int solve(int[] values){
- int root = nodes.get(values[0]);
- int target = nodes.get(values[1]);
- int n = root;
- int count = 0;
- while(true){
- n = nodes.get(n);
- if(n == root) return -1; //Not in friend's circle
- if(n == target) return count; //Is in friend's circle
- count++;
- }
- }
- private void outputAnswer(int answer){
- if(answer == -1) System.out.println("No");
- else System.out.println("Yes " + answer);
- }
- public static void main(String[] args){
- Friends f = new Friends();
- f.getInput();
- for(int[] i : f.values){
- int ans = f.solve(i);
- f.outputAnswer(ans);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement