結果

問題 No.277 根掘り葉掘り
ユーザー uafr_csuafr_cs
提出日時 2015-09-04 22:54:28
言語 Java21
(openjdk 21)
結果
AC  
実行時間 2,002 ms / 3,000 ms
コード長 1,902 bytes
コンパイル時間 2,393 ms
コンパイル使用メモリ 77,396 KB
実行使用メモリ 115,744 KB
最終ジャッジ日時 2023-09-26 06:09:42
合計ジャッジ時間 26,315 ms
ジャッジサーバーID
(参考情報)
judge11 / judge13
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 127 ms
56,036 KB
testcase_01 AC 126 ms
55,600 KB
testcase_02 AC 125 ms
56,188 KB
testcase_03 AC 154 ms
55,536 KB
testcase_04 AC 163 ms
57,824 KB
testcase_05 AC 161 ms
55,948 KB
testcase_06 AC 155 ms
55,644 KB
testcase_07 AC 155 ms
55,588 KB
testcase_08 AC 133 ms
55,916 KB
testcase_09 AC 1,925 ms
106,048 KB
testcase_10 AC 1,817 ms
115,744 KB
testcase_11 AC 1,847 ms
109,704 KB
testcase_12 AC 1,963 ms
110,776 KB
testcase_13 AC 1,949 ms
104,152 KB
testcase_14 AC 2,002 ms
114,716 KB
testcase_15 AC 1,833 ms
114,068 KB
testcase_16 AC 1,865 ms
106,728 KB
testcase_17 AC 1,935 ms
110,352 KB
testcase_18 AC 1,824 ms
108,004 KB
testcase_19 AC 1,855 ms
108,944 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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]));
		}
		
	}

}
0