結果

問題 No.994 ばらばらコイン
ユーザー tentententen
提出日時 2022-09-13 18:05:28
言語 Java21
(openjdk 21)
結果
WA  
実行時間 -
コード長 1,887 bytes
コンパイル時間 1,762 ms
コンパイル使用メモリ 75,804 KB
実行使用メモリ 78,668 KB
最終ジャッジ日時 2023-08-20 19:42:12
合計ジャッジ時間 6,396 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 WA -
testcase_02 AC 37 ms
49,360 KB
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 AC 38 ms
49,320 KB
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 AC 36 ms
49,460 KB
testcase_17 AC 40 ms
49,364 KB
testcase_18 AC 37 ms
49,208 KB
testcase_19 AC 37 ms
49,304 KB
testcase_20 AC 36 ms
49,356 KB
testcase_21 WA -
testcase_22 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.*;
import java.util.*;

public class Main {
    static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
    static int[] depths;
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner();
        int n = sc.nextInt();
        int k = sc.nextInt();
        if (k > n) {
            System.out.println(-1);
            return;
        }
        for (int i = 0; i < n; i++) {
            graph.add(new ArrayList<>());
        }
        for (int i = 0; i < n - 1; i++) {
            int a = sc.nextInt() - 1;
            int b = sc.nextInt() - 1;
            graph.get(a).add(b);
            graph.get(b).add(a);
        }
        depths = new int[n];
        setDepth(0, 0, 0);
        Arrays.sort(depths);
        long ans = 0;
        for (int i = 0; i < k; i++) {
            ans += depths[i];
        }
        System.out.println(ans);
    }
    
    static void setDepth(int idx, int p, int d) {
        depths[idx] = d;
        for (int x : graph.get(idx)) {
            if (x == p) {
                continue;
            }
            setDepth(x, idx, d + 1);
        }
    }
}
    
class Scanner {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st = new StringTokenizer("");
    StringBuilder sb = new StringBuilder();
    
    public Scanner() throws Exception {
        
    }
    
    public int nextInt() throws Exception {
        return Integer.parseInt(next());
    }
    
    public long nextLong() throws Exception {
        return Long.parseLong(next());
    }
    
    public double nextDouble() throws Exception {
        return Double.parseDouble(next());
    }
    
    public String next() throws Exception {
        while (!st.hasMoreTokens()) {
            st = new StringTokenizer(br.readLine());
        }
        return st.nextToken();
    }
    
}
0