結果
問題 | No.277 根掘り葉掘り |
ユーザー |
![]() |
提出日時 | 2020-10-05 09:56:46 |
言語 | Java (openjdk 23) |
結果 |
WA
|
実行時間 | - |
コード長 | 1,360 bytes |
コンパイル時間 | 2,359 ms |
コンパイル使用メモリ | 79,284 KB |
実行使用メモリ | 88,548 KB |
最終ジャッジ日時 | 2024-07-19 19:24:15 |
合計ジャッジ時間 | 18,081 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 10 WA * 8 |
ソースコード
import java.util.*; public class Main { static ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); static int[] roots; static int[] leaves; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); roots = new int[n]; leaves = new int[n]; for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } for (int i = 0; i < n - 1; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; graph.get(a).add(b); graph.get(b).add(a); } getDist(0, 0, 0); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(Math.min(roots[i], leaves[i])).append("\n"); } System.out.print(sb); } static int getDist(int idx, int parent, int depth) { roots[idx] = depth; if (idx != 0 && graph.get(idx).size() == 1) { leaves[idx] = 0; } else { int min = Integer.MAX_VALUE; for (int x : graph.get(idx)) { if (x == parent) { continue; } min = Math.min(min, getDist(x, idx, depth + 1)); } leaves[idx] = min; } return leaves[idx] + 1; } }