結果

問題 No.277 根掘り葉掘り
ユーザー uafr_csuafr_cs
提出日時 2015-09-04 23:22:41
言語 Java21
(openjdk 21)
結果
WA  
実行時間 -
コード長 1,775 bytes
コンパイル時間 3,174 ms
コンパイル使用メモリ 76,476 KB
実行使用メモリ 113,836 KB
最終ジャッジ日時 2023-09-26 06:50:27
合計ジャッジ時間 25,023 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 AC 121 ms
56,280 KB
testcase_02 AC 123 ms
55,992 KB
testcase_03 AC 149 ms
56,084 KB
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 AC 147 ms
56,264 KB
testcase_08 AC 123 ms
56,268 KB
testcase_09 AC 1,650 ms
105,396 KB
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 AC 1,752 ms
103,572 KB
testcase_14 AC 1,727 ms
105,904 KB
testcase_15 AC 1,684 ms
104,536 KB
testcase_16 AC 1,664 ms
101,780 KB
testcase_17 AC 1,613 ms
101,892 KB
testcase_18 AC 1,703 ms
106,624 KB
testcase_19 AC 1,731 ms
106,476 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> leafs = new HashSet<Integer>();
		for(int i = 0; i < N; i++){
			if(degrees[i] == 1){
				leafs.add(i);
			}
		}
		
		int[] leaf_dist = bfs(N, adj, leafs);
		
		for(int i = 0; i < N; i++){
			System.out.println(leaf_dist[i]);
		}
		
	}

}
0