結果

問題 No.994 ばらばらコイン
ユーザー joybeeeejoybeeee
提出日時 2020-05-14 22:30:45
言語 Java21
(openjdk 21)
結果
AC  
実行時間 1,144 ms / 2,000 ms
コード長 1,169 bytes
コンパイル時間 2,290 ms
コンパイル使用メモリ 76,152 KB
実行使用メモリ 95,212 KB
最終ジャッジ日時 2023-10-14 08:14:22
合計ジャッジ時間 16,063 ms
ジャッジサーバーID
(参考情報)
judge11 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 123 ms
55,648 KB
testcase_01 AC 140 ms
56,352 KB
testcase_02 AC 982 ms
95,212 KB
testcase_03 AC 1,046 ms
87,808 KB
testcase_04 AC 1,013 ms
87,328 KB
testcase_05 AC 694 ms
68,568 KB
testcase_06 AC 1,144 ms
92,312 KB
testcase_07 AC 1,013 ms
87,408 KB
testcase_08 AC 943 ms
80,688 KB
testcase_09 AC 954 ms
81,412 KB
testcase_10 AC 842 ms
77,132 KB
testcase_11 AC 1,047 ms
82,892 KB
testcase_12 AC 974 ms
82,040 KB
testcase_13 AC 127 ms
55,612 KB
testcase_14 AC 126 ms
55,728 KB
testcase_15 AC 125 ms
56,140 KB
testcase_16 AC 124 ms
56,756 KB
testcase_17 AC 126 ms
55,960 KB
testcase_18 AC 124 ms
55,796 KB
testcase_19 AC 124 ms
55,732 KB
testcase_20 AC 125 ms
55,552 KB
testcase_21 AC 123 ms
55,792 KB
testcase_22 AC 126 ms
55,508 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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