結果
| 問題 |
No.277 根掘り葉掘り
|
| コンテスト | |
| ユーザー |
htensai
|
| 提出日時 | 2020-05-12 11:57:20 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 1,461 ms / 3,000 ms |
| コード長 | 1,327 bytes |
| コンパイル時間 | 2,582 ms |
| コンパイル使用メモリ | 80,344 KB |
| 実行使用メモリ | 86,144 KB |
| 最終ジャッジ日時 | 2024-09-13 06:41:54 |
| 合計ジャッジ時間 | 21,216 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 18 |
ソースコード
import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
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);
}
int[] costs = new int[n];
Arrays.fill(costs, Integer.MAX_VALUE);
PriorityQueue<Path> queue = new PriorityQueue<>();
queue.add(new Path(0, 0));
while (queue.size() > 0) {
Path p = queue.poll();
if (graph.get(p.idx).size() == 1) {
p.value = 0;
}
if (costs[p.idx] <= p.value) {
continue;
}
costs[p.idx] = p.value;
for (int x : graph.get(p.idx)) {
queue.add(new Path(x, p.value + 1));
}
}
StringBuilder sb = new StringBuilder();
for (int x : costs) {
sb.append(x).append("\n");
}
System.out.print(sb);
}
static class Path implements Comparable<Path> {
int idx;
int value;
public Path(int idx, int value) {
this.idx = idx;
this.value = value;
}
public int compareTo(Path another) {
return value - another.value;
}
}
}
htensai