Advertisement
Yesver08

Untitled

Jan 31st, 2023
651
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4.     public static int getDepth(Node node) {
  5.         if (node == null) {
  6.             return 0;
  7.         }
  8.         if (node.childs.size() == 0) {
  9.             return 1;
  10.         }
  11.         int maxDepth = 0;
  12.         for (Node child : node.childs) {
  13.             int depth = 1 + getDepth(child);
  14.             if (depth > maxDepth) maxDepth = depth;
  15.         }
  16.         return maxDepth;
  17.     }
  18.    
  19.     public static int predators(ArrayList<Integer> datas) {
  20.         ArrayList<Node> nodes = new ArrayList<>();
  21.         ArrayList<Node> parents = new ArrayList<>();
  22.        
  23.         for (int i = 0; i < datas.size(); i++) {
  24.             nodes.add(new Node(i));
  25.         }
  26.        
  27.         for (int i = 0; i < datas.size(); i++) {
  28.             int data = datas.get(i);
  29.             Node node = nodes.get(i);
  30.            
  31.             if (data == -1) {
  32.                 parents.add(node);
  33.             }
  34.             else {
  35.                 Node parent = nodes.get(data);
  36.                 parent.childs.add(node);
  37.                 node.parent = parent;
  38.             }
  39.         }
  40.        
  41.         int maxDepth = 0;
  42.         for (Node parent : parents) {
  43.             int depth = getDepth(parent);
  44.             if (depth > maxDepth) maxDepth = depth;
  45.         }
  46.         return maxDepth;
  47.     }
  48.    
  49.     public static void main(String[] args) {
  50.         Scanner sc = new Scanner(System.in);
  51.        
  52.         ArrayList<Integer> data = new ArrayList<>();
  53.         while (sc.hasNext()) {
  54.             int n = sc.nextInt();
  55.             data.add(n);
  56.         }
  57.        
  58.         System.out.println(predators(data));
  59.     }
  60. }
  61.  
  62. class Node {
  63.     Node parent;
  64.     int data;
  65.     ArrayList<Node> childs;
  66.    
  67.     public Node(int data) {
  68.         this.data = data;
  69.         childs = new ArrayList<>();
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement