import org.omg.CORBA.INTERNAL; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; class TreeNode{ TreeNode left; TreeNode right; int val; public TreeNode(int val) { this.val = val; left = null; right = null; } } public class Main { public static Scanner sc = new Scanner(System.in); public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static long mod = (long) Math.pow(2, 29); public static void main(String[] args) throws Exception { String line; String[] strArr; line = reader.readLine(); strArr = line.split(" "); int n = Integer.valueOf(strArr[0]); int rootVal = Integer.valueOf(strArr[1]); Map<Integer, TreeNode> mp = new HashMap<>(n); for (int i = 0; i < n; i++) { line = reader.readLine(); strArr = line.split(" "); int val = Integer.valueOf(strArr[0]); int leftVal = Integer.valueOf(strArr[1]); int rightVal = Integer.valueOf(strArr[2]); if (!mp.containsKey(val)) { mp.put(val, new TreeNode(val)); } if (leftVal != 0) { if (!mp.containsKey(leftVal)) { mp.put(leftVal, new TreeNode(leftVal)); } mp.get(val).left = mp.get(leftVal); } if (rightVal != 0) { if (!mp.containsKey(rightVal)) { mp.put(rightVal, new TreeNode(rightVal)); } mp.get(val).right = mp.get(rightVal); } } TreeNode root = mp.get(rootVal); System.out.println(getMaxLen(root)); } static int getMaxLen(TreeNode root){ if(root == null){ return 0; } int leftLen = getMaxLen(root.left); int rightLen = getMaxLen(root.right); int rootMaxLen = getMaxSinglePath(root.left) + getMaxSinglePath(root.right) + 1; return Math.max(Math.max(leftLen, rightLen), rootMaxLen); } // static int getMaxLenBySingle(int leftMaxLen, int rightMaxLen){ // if(leftMaxLen == 0 && rightMaxLen == 0){ // return 1; // }else if(rightMaxLen == 0){ // return leftMaxLen; // }else if(leftMaxLen == 0){ // return rightMaxLen; // }else { // return leftMaxLen + rightMaxLen - 1; // } // } // 以 root 为节点的,左边 或者 右边最大单路径 static int getMaxSinglePath(TreeNode root){ if(root == null){ return 0; } int leftPath = getMaxSinglePath(root.left); int rightPath = getMaxSinglePath(root.right); return Math.max(leftPath, rightPath) + 1; } } /* 1 / \ 2 3 / \ / \ 4 5 6 7 / 8 8 1 1 2 3 2 4 5 4 0 0 5 0 0 3 6 7 6 0 0 7 8 0 8 0 0 6 1 / \ 2 3 / \ / \ 4 5 6 7 7 1 1 2 3 2 4 5 4 0 0 5 0 0 3 6 7 6 0 0 7 0 0 5 */