結果

問題 No.994 ばらばらコイン
ユーザー Mishan5055Mishan5055
提出日時 2020-03-27 17:33:11
言語 Java21
(openjdk 21)
結果
WA  
実行時間 -
コード長 1,775 bytes
コンパイル時間 2,258 ms
コンパイル使用メモリ 74,472 KB
実行使用メモリ 68,624 KB
最終ジャッジ日時 2023-08-30 16:35:41
合計ジャッジ時間 13,201 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 WA -
testcase_02 AC 698 ms
66,580 KB
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 AC 574 ms
64,060 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 124 ms
55,916 KB
testcase_17 AC 125 ms
55,808 KB
testcase_18 AC 124 ms
55,896 KB
testcase_19 AC 127 ms
56,196 KB
testcase_20 AC 128 ms
55,720 KB
testcase_21 WA -
testcase_22 WA -
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

class Main{
    static int INF=100000007;
    static class edge implements Comparable<edge>{
        int from;
        int to;
        
        void edge(int from,int to){
            this.from=from;
            this.to=to;
        }
        
        public int compareTo(edge e){
            return this.from-e.from;
        }
    }
    
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int N=sc.nextInt();
        int K=sc.nextInt();
        edge[] graph=new edge[N-1];
        int[] dist=new int[N];
        
        for(int i=0;i<N;i++){
            dist[i]=INF;
        }
        
        dist[0]=0;
        
        for(int i=0;i<N-1;i++){
            edge e=new edge();
            e.edge(sc.nextInt()-1,sc.nextInt()-1);
            graph[i]=e;
        }
        
        Arrays.sort(graph);
        
        boolean change=false;
        
        while(true){
            change=false;
            for(int i=0;i<N-1;i++){
                int start=graph[i].from;
                int end=graph[i].to;
                
                if(dist[start]!=INF&&dist[end]>dist[start]+1){
                    dist[end]=dist[start]+1;
                    change=true;
                }
            }
            
            if(!change){
                break;
            }
        }
        
        int count=0;
        
        for(int i=0;i<N;i++){
            if(dist[i]!=INF){
                count++;
            }
        }
        
        if(count<K){
            System.out.println("-1");
            return;
        }
        
        Arrays.sort(dist);
        int ans=0;
        
        for(int i=0;i<K;i++){
            ans+=dist[i];
        }
        
        System.out.println(ans);
    }
}
0