publicstaticvoidmain(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(), x = scan.nextInt(), y = scan.nextInt(); List<Integer>[] lists = new List[n+1]; for(int i = 0; i < n-1; i++){ int u = scan.nextInt(), v = scan.nextInt(); lists[u] = lists[u] == null ? new ArrayList<>() : lists[u]; lists[v] = lists[v] == null ? new ArrayList<>() : lists[v]; lists[u].add(v); lists[v].add(u); }
int[] dist1 = getDistance(x, n, lists); int[] dist2 = getDistance(y, n, lists);
int res = 0; for(int i = 1; i <= n; i++){ if(dist1[i] > dist2[i]){ res = Math.max(res, dist1[i]); } }
System.out.println(res);
} // 迪杰斯特拉算法求单源最短路径(还可以通过BFS算法求) privatestaticint[] getDistance(int start, int n, List<Integer>[] lists) {
publicstaticvoidmain(String[] args){ Scanner scan = new Scanner(System.in); int m = scan.nextInt(), n = scan.nextInt(); int[] nums = newint[n]; for(int i = 0; i < n; i++){ nums[i] = scan.nextInt(); }
int ct = 0; int l, r, i; int star = 1;
// 虽然n的数量级时10^5, 但加入了两处剪枝后,可以大幅降低时间复杂度 for(l = 1; l <= m; l++){ for(r = star; r <= m; r++){ // l时的r必然是l-1时r的子集---第二处剪枝 int pre = 0; for(i = 0; i < n; i++){ if(nums[i] < l || nums[i] > r){ if(nums[i] < pre){ break; } pre = nums[i]; } } if(i == n){ // 子序列是非降序排列---第一处剪枝-1 break; } } if(r <= m){ // [r, m]必然满足---第一处剪枝-2 ct += m - r + 1; } star = r; }