結果
| 問題 |
No.812 Change of Class
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2019-11-12 21:05:41 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
AC
|
| 実行時間 | 3,548 ms / 4,000 ms |
| コード長 | 2,313 bytes |
| コンパイル時間 | 175 ms |
| コンパイル使用メモリ | 82,100 KB |
| 実行使用メモリ | 248,228 KB |
| 最終ジャッジ日時 | 2024-06-12 21:46:46 |
| 合計ジャッジ時間 | 68,346 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 60 |
ソースコード
from heapq import heappush, heappop
class UnionFind :
def __init__(self, size) :
self.parent = list(range(size))
self.height = [0] * size
self.size = [1] * size
self.component = size
def root(self, index) :
if self.parent[index] == index : # 根の場合
return index
rootIndex = self.root(self.parent[index]) # 葉の場合親の根を取得
self.parent[index] = rootIndex # 親の付け直し
return rootIndex
def union(self, index1, index2) : # 結合
root1 = self.root(index1)
root2 = self.root(index2)
if root1 == root2 : # 連結されている場合
return
self.component -= 1 # 連結成分を減らす
if self.height[root1] < self.height[root2] :
self.parent[root1] = root2 # root2に結合
self.size[root2] += self.size[root1]
else :
self.parent[root2] = root1 # root1に結合
self.size[root1] += self.size[root2]
if self.height[root1] == self.height[root2] :
self.height[root1] += 1
return
def isSameRoot(self, index1, index2) :
return self.root(index1) == self.root(index2)
def sizeOfSameRoot(self, index) :
return self.size[self.root(index)]
def getComponent(self) :
return self.component
N, M = map(int, input().split())
tree = UnionFind(N)
edges = [[] for _ in range(N)]
for _ in range(M):
p, q = map(int, input().split())
p -= 1
q -= 1
tree.union(p, q)
edges[p].append(q)
edges[q].append(p)
def search(start):
que = [(0, start)]
minDist = [float('inf')] * N
while que:
d, now = heappop(que)
if minDist[now] <= d:
continue
minDist[now] = d
for to in edges[now]:
if minDist[to] > d + 1:
heappush(que, (d + 1, to))
D = [d - 1 for d in minDist if 1 <= d and d != float('inf')]
if D:
return max(D)
else:
return 0
# Qが十分小さい
Q = int(input())
ans = []
for _ in range(Q):
A = int(input())
A -= 1
dist = search(A)
day = 0
while (1 << day) <= dist:
day += 1
ans.append((tree.sizeOfSameRoot(A) - 1, day))
for a, b in ans:
print(a, b)