結果
| 問題 | No.922 東北きりきざむたん |
| コンテスト | |
| ユーザー |
maspy
|
| 提出日時 | 2020-05-16 13:19:30 |
| 言語 | Python3 (3.13.1 + numpy 2.2.1 + scipy 1.14.1) |
| 結果 |
AC
|
| 実行時間 | 1,360 ms / 2,000 ms |
| コード長 | 2,131 bytes |
| コンパイル時間 | 301 ms |
| コンパイル使用メモリ | 13,056 KB |
| 実行使用メモリ | 60,796 KB |
| 最終ジャッジ日時 | 2024-09-22 06:45:25 |
| 合計ジャッジ時間 | 18,697 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 26 |
ソースコード
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N, M, Q = map(int, readline().split())
G = [[] for _ in range(N + 1)]
for _ in range(M):
a, b = map(int, readline().split())
G[a].append(b)
G[b].append(a)
root = [0] * (N + 1)
parent = [0] * (N + 1)
depth = [0] * (N + 1)
stack = []
order = []
for r in range(1, N + 1):
if root[r]:
continue
root[r] = 0
depth[r] = 1
stack = [r]
while stack:
v = stack.pop()
root[v] = r
order.append(v)
for w in G[v]:
if w == parent[v]:
continue
parent[w] = v
depth[w] = depth[v] + 1
stack.append(w)
def dist_func():
K = 18
P = [parent]
for i in range(1, K):
A = P[-1]
P.append([A[v] for v in A])
def LCA(u, v):
du, dv = depth[u], depth[v]
if du < dv:
du, dv = dv, du
u, v = v, u
n = du - dv
for i in range(K):
if n & 1:
u = P[i][u]
n >>= 1
if u == v:
return u
for i in range(K - 1, -1, -1):
u1, v1 = P[i][u], P[i][v]
if u1 == v1:
continue
u, v = u1, v1
return parent[u]
def dist(u, v):
w = LCA(u, v)
return depth[u] + depth[v] - 2 * depth[w]
return dist
dist = dist_func()
dp_size = [0] * (N + 1)
dp_sum = [0] * (N + 1)
m = map(int, read().split())
answer = 0
for a, b in zip(m, m):
if root[a] == root[b]:
answer += dist(a, b)
else:
dp_size[a] += 1
dp_size[b] += 1
for v in order[::-1]:
p = parent[v]
dp_sum[p] += dp_sum[v] + dp_size[v]
dp_size[p] += dp_size[v]
comp_cost = [0] * (N + 1)
for v in order:
r, p = root[v], parent[v]
if v == r:
comp_cost[v] = dp_sum[v]
continue
lower, upper = dp_size[v], dp_size[r] - dp_size[v]
dp_sum[v] = dp_sum[p] + upper - lower
if comp_cost[r] > dp_sum[v]:
comp_cost[r] = dp_sum[v]
answer += sum(comp_cost)
print(answer)
maspy