結果
| 問題 |
No.994 ばらばらコイン
|
| コンテスト | |
| ユーザー |
Ohnuma
|
| 提出日時 | 2020-04-10 14:18:24 |
| 言語 | Python3 (3.13.1 + numpy 2.2.1 + scipy 1.14.1) |
| 結果 |
AC
|
| 実行時間 | 403 ms / 2,000 ms |
| コード長 | 2,005 bytes |
| コンパイル時間 | 102 ms |
| コンパイル使用メモリ | 12,672 KB |
| 実行使用メモリ | 12,288 KB |
| 最終ジャッジ日時 | 2024-09-15 01:19:46 |
| 合計ジャッジ時間 | 6,028 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 23 |
ソースコード
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)
Ohnuma