結果

問題 No.994 ばらばらコイン
ユーザー OhnumaOhnuma
提出日時 2020-04-10 14:18:24
言語 Python3
(3.11.6 + numpy 1.26.0 + scipy 1.11.3)
結果
AC  
実行時間 335 ms / 2,000 ms
コード長 2,005 bytes
コンパイル時間 77 ms
コンパイル使用メモリ 11,032 KB
実行使用メモリ 9,872 KB
最終ジャッジ日時 2023-10-13 03:39:43
合計ジャッジ時間 5,349 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 16 ms
8,188 KB
testcase_01 AC 16 ms
8,212 KB
testcase_02 AC 323 ms
9,868 KB
testcase_03 AC 335 ms
9,824 KB
testcase_04 AC 330 ms
9,872 KB
testcase_05 AC 174 ms
9,160 KB
testcase_06 AC 330 ms
9,868 KB
testcase_07 AC 332 ms
9,792 KB
testcase_08 AC 230 ms
9,380 KB
testcase_09 AC 306 ms
9,804 KB
testcase_10 AC 229 ms
9,344 KB
testcase_11 AC 259 ms
9,468 KB
testcase_12 AC 282 ms
9,684 KB
testcase_13 AC 16 ms
8,328 KB
testcase_14 AC 16 ms
8,324 KB
testcase_15 AC 16 ms
8,248 KB
testcase_16 AC 17 ms
8,320 KB
testcase_17 AC 15 ms
8,372 KB
testcase_18 AC 15 ms
8,244 KB
testcase_19 AC 16 ms
8,216 KB
testcase_20 AC 16 ms
8,324 KB
testcase_21 AC 16 ms
8,324 KB
testcase_22 AC 16 ms
8,208 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

class UnionFind:
    """
        n : 要素数
        root : 親ノード
        size : グループのサイズ
    """
    
    def __init__(self, n):
        self.n = n
        self.root = [-1]*(n+1)
        self.size = [1]*(n+1)
    
    """ノードxのrootノードを見つける"""
    def Find_Root(self, x):
        if self.root[x] < 0:
            return x
        else:
            self.root[x] = self.Find_Root(self.root[x])
            return self.root[x]
    
    """木の合併"""
    def Union(self, x, y):
        #入力ノードの親を探索
        x = self.Find_Root(x)
        y = self.Find_Root(y)
        
        #既に同じ木に所属する場合
        if x==y:
            return 
        
        #異なる木に所属する場合 -> sizeが小さい方から大きい方に合併する
        elif self.size[x] > self.size[y]:
            self.size[x] += self.size[y]
            self.root[y] = x
        
        else:
            self.size[y] += self.size[x]
            self.root[x] = y
    
    """xとyが同じグループに所属するか"""
    # 辺(x,y)が橋の場合 : isSameGroup(self, x, y)=False
    def isSameGroup(self, x, y):
        return self.Find_Root(x) == self.Find_Root(y)
       
    """ 頂点数を数える"""
    #全連結成分にするために必要な橋の本数は、cnt - 1
    def Count_Vertex(self):
        cnt = 0
        for i in range(self.n):
            if self.root[i+1] < 0:
                cnt += 1
        return cnt
    
    """ xが属する集合に含まれる全ノードを返す """
    def Members(self, x):
        r = self.Find_Root(x)
        return [i for i in range(self.n+1) if self.Find_Root(i) == r]
    
    """xが属する集合のサイズ"""
    def Size(self, x):
        return self.size[self.Find_Root(x)]
    
n,k = map(int,input().split())
uf = UnionFind(n)
for _ in range(n-1):
    a,b = map(int,input().split())
    uf.Union(a,b)

if k>uf.Size(1):
    print(-1)
else:
    print(k-1)
0