Tiger_Li level
获赞
3
粉丝
0
关注
6
看过 TA
77
University of Maryland College Park
2022
数据分析师
IP属地:浙江
暂未填写个人简介
私信
关注
资略高 技术岗 20,000-20,000
0 点赞 评论 收藏
分享
_叶知秋:BFS:100% public class Main5 { static List<Integer>[] edges; static boolean[] vis; static int n; static int[] val; // 贪心,从最小的节点出发,dfs,且最小节点值只能有1个 public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for (int j = 0; j < t; ++j) { n = scanner.nextInt(); // 节点编号1-n edges = new List[n + 1]; vis = new boolean[n + 1]; for (int i = 0; i <= n; i++) { edges[i] = new ArrayList<>(); } int[] a = new int[n - 1]; int[] b = new int[n - 1]; for (int i = 0; i < n - 1; i++) { a[i] = scanner.nextInt(); } for (int i = 0; i < n - 1; i++) { b[i] = scanner.nextInt(); } for (int i = 0; i < n - 1; i++) { edges[a[i]].add(b[i]); edges[b[i]].add(a[i]); } val = new int[n + 1]; int minVal = Integer.MAX_VALUE; int minNode = 0; for (int i = 1; i <= n; i++) { int x = scanner.nextInt(); if (x < minVal) { minVal = x; minNode = i; } val[i] = x; } Queue<Integer> queue = new LinkedList<>(); queue.offer(minNode); vis[minNode] = true; boolean flag = true; while (!queue.isEmpty() &;&; flag) { int size = queue.size(); for (int i = 0; i < size; i++) { int p = queue.poll(); for (int child : edges[p]) { if (vis[child]) { continue; } if (val[child] <= val[p]) { flag = false; break; } queue.offer(child); vis[child] = true; } if (!flag) { break; } } } System.out.println(flag ? minNode : -1); } } }
投递美团等公司10个岗位
0 点赞 评论 收藏
分享
关注他的用户也关注了:
牛客网
牛客企业服务