結果
問題 |
No.994 ばらばらコイン
|
ユーザー |
![]() |
提出日時 | 2020-05-14 22:30:45 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 1,184 ms / 2,000 ms |
コード長 | 1,169 bytes |
コンパイル時間 | 2,150 ms |
コンパイル使用メモリ | 80,284 KB |
実行使用メモリ | 85,688 KB |
最終ジャッジ日時 | 2024-09-16 03:21:53 |
合計ジャッジ時間 | 14,511 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 23 |
ソースコード
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); Map<Integer, List<Integer>> graph = new HashMap<>(); for(int i = 1; i <= n; i++) graph.put(i, new ArrayList<>()); for(int i = 0; i < n-1; i++) { int a = sc.nextInt(); int b = sc.nextInt(); graph.get(a).add(b); graph.get(b).add(a); } Queue<Integer> queue = new LinkedList<>(); queue.offer(1); Set<Integer> visited = new HashSet<>(); visited.add(1); k--; int steps = 0; if(k == 0) { System.out.println(steps); return; } while(!queue.isEmpty()) { int node = queue.poll(); List<Integer> adj = graph.get(node); for(int adjNode : adj) { if(visited.contains(adjNode)) continue; visited.add(adjNode); queue.offer(adjNode); k--; steps++; if(k == 0) { System.out.println(steps); return; } } } System.out.println(-1); } }