Advertisement
Guest User

Untitled

a guest
Nov 25th, 2017
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.Scanner;
  5.  
  6. public class Friends {
  7. private ArrayList<int[]> values = new ArrayList<>();
  8. private Map<Integer, Integer> nodes;
  9. private Scanner in = new Scanner(System.in);
  10.  
  11. private void getInput(){
  12. int n = in.nextInt();
  13. nodes = new HashMap<>(n);
  14.  
  15. //Populate friends map
  16. for(int i = 0; i < n; i++){
  17. int n1 = in.nextInt();
  18. int n2 = in.nextInt();
  19.  
  20. nodes.put(n1, n2);
  21. }
  22.  
  23. //Test cases
  24. while(true){
  25. int n1 = in.nextInt();
  26. int n2 = in.nextInt();
  27.  
  28. if(n1 == 0 && n2 == 0) break;
  29.  
  30. values.add(new int[]{n1, n2});
  31. }
  32. }
  33.  
  34. public int solve(int[] values){
  35. int root = nodes.get(values[0]);
  36. int target = nodes.get(values[1]);
  37. int n = root;
  38. int count = 0;
  39.  
  40. while(true){
  41. n = nodes.get(n);
  42.  
  43. if(n == root) return -1; //Not in friend's circle
  44. if(n == target) return count; //Is in friend's circle
  45.  
  46. count++;
  47. }
  48. }
  49.  
  50. private void outputAnswer(int answer){
  51. if(answer == -1) System.out.println("No");
  52. else System.out.println("Yes " + answer);
  53. }
  54.  
  55. public static void main(String[] args){
  56. Friends f = new Friends();
  57. f.getInput();
  58.  
  59. for(int[] i : f.values){
  60. int ans = f.solve(i);
  61. f.outputAnswer(ans);
  62. }
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement