結果
問題 | No.277 根掘り葉掘り |
ユーザー |
![]() |
提出日時 | 2015-09-04 22:54:28 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 2,332 ms / 3,000 ms |
コード長 | 1,902 bytes |
コンパイル時間 | 2,359 ms |
コンパイル使用メモリ | 79,544 KB |
実行使用メモリ | 114,548 KB |
最終ジャッジ日時 | 2024-07-19 01:30:57 |
合計ジャッジ時間 | 27,170 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 18 |
ソースコード
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Scanner; import java.util.Set; public class Main { public static int INF = Integer.MAX_VALUE / 2 - 1; public static int[] bfs(final int N, ArrayList<LinkedHashSet<Integer>> adj, Set<Integer> starts){ int[] costs = new int[N]; Arrays.fill(costs, INF); LinkedList<Integer> node_queue = new LinkedList<Integer>(); boolean[] in_queue = new boolean[N]; for(final int start : starts){ costs[start] = 0; node_queue.add(start); in_queue[start] = true; } while(!node_queue.isEmpty()){ final int node = node_queue.poll(); in_queue[node] = false; for(final int next : adj.get(node)){ final int next_cost = costs[node] + 1; if(next_cost >= costs[next]){ continue; } costs[next] = next_cost; if(!in_queue[next]){ node_queue.add(next); } } } return costs; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); final int N = sc.nextInt(); ArrayList<LinkedHashSet<Integer>> adj = new ArrayList<LinkedHashSet<Integer>>(); for(int i = 0; i < N; i++){ adj.add(new LinkedHashSet<Integer>()); } int[] degrees = new int[N]; for(int i = 0; i < N - 1; i++){ final int x = sc.nextInt() - 1; final int y = sc.nextInt() - 1; degrees[x]++; degrees[y]++; adj.get(x).add(y); adj.get(y).add(x); } Set<Integer> root = new HashSet<Integer>(); root.add(0); Set<Integer> leafs = new HashSet<Integer>(); for(int i = 0; i < N; i++){ if(degrees[i] == 1){ leafs.add(i); } } int[] root_dist = bfs(N, adj, root); int[] leaf_dist = bfs(N, adj, leafs); for(int i = 0; i < N; i++){ System.out.println(Math.min(root_dist[i], leaf_dist[i])); } } }