Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Main {
- public static int getDepth(Node node) {
- if (node == null) {
- return 0;
- }
- if (node.childs.size() == 0) {
- return 1;
- }
- int maxDepth = 0;
- for (Node child : node.childs) {
- int depth = 1 + getDepth(child);
- if (depth > maxDepth) maxDepth = depth;
- }
- return maxDepth;
- }
- public static int predators(ArrayList<Integer> datas) {
- ArrayList<Node> nodes = new ArrayList<>();
- ArrayList<Node> parents = new ArrayList<>();
- for (int i = 0; i < datas.size(); i++) {
- nodes.add(new Node(i));
- }
- for (int i = 0; i < datas.size(); i++) {
- int data = datas.get(i);
- Node node = nodes.get(i);
- if (data == -1) {
- parents.add(node);
- }
- else {
- Node parent = nodes.get(data);
- parent.childs.add(node);
- node.parent = parent;
- }
- }
- int maxDepth = 0;
- for (Node parent : parents) {
- int depth = getDepth(parent);
- if (depth > maxDepth) maxDepth = depth;
- }
- return maxDepth;
- }
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- ArrayList<Integer> data = new ArrayList<>();
- while (sc.hasNext()) {
- int n = sc.nextInt();
- data.add(n);
- }
- System.out.println(predators(data));
- }
- }
- class Node {
- Node parent;
- int data;
- ArrayList<Node> childs;
- public Node(int data) {
- this.data = data;
- childs = new ArrayList<>();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement