結果

問題 No.2892 Lime and Karin
ユーザー adapchi
提出日時 2024-09-13 23:40:17
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 3,836 ms / 8,000 ms
コード長 1,385 bytes
コンパイル時間 2,909 ms
コンパイル使用メモリ 81,900 KB
実行使用メモリ 142,364 KB
最終ジャッジ日時 2024-09-13 23:42:01
合計ジャッジ時間 93,698 ms
ジャッジサーバーID
(参考情報)
judge6 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 52
権限があれば一括ダウンロードができます

ソースコード

diff #

N = int(input())

G = [[] for _ in range(N)]
for _ in range(N - 1):
  u, v = [int(x) - 1 for x in input().split()]
  G[u].append(v)
  G[v].append(u)
  
S = [1 if x == '1' else -1 for x in input()]

used = [False] * N
size = [0] * N
def centroid(x):
  stk = [(x, None, 0)]
  while stk:
    u, p, t = stk.pop()
    if t == 0:
      stk.append((u, p, 1))
      stk.extend((v, u, 0) for v in G[u] if not used[v] and v != p)
    else:
      size[u] = 1 + sum(size[v] for v in G[u] if not used[v] and v != p)
  
  p = None
  s = size[x]
  try:
    while True:
      x, p = next(y for y in G[x] if not used[y] and y != p and size[y] * 2 > s), x
  except StopIteration:
    return x
  
def paths(x, p):
  stk = [(x, p, S[x])]
  res = []
  while stk:
    u, p, d = stk.pop()
    res.append(d)
    stk.extend((v, u, d + S[v]) for v in G[u] if not used[v] and v != p)
  return res
  
def pairs(xs, y):
  xs.sort()
  res = 0
  i = len(xs)
  for x in xs:
    while i >= 1 and x + xs[i - 1] + y > 0:
      i -= 1
    res += len(xs) - i
  return res
        
stk = [0]
ans = 0
while stk:
  u = centroid(stk.pop())
  if S[u] == 1: ans += 1
  
  vs = [v for v in G[u] if not used[v]]
  stk.extend(vs)
  
  ds = [paths(v, u) for v in vs]
  ans += sum(x + S[u] > 0 for d in ds for x in d)
  ans += (pairs(sum(ds, start=[]), S[u]) - sum(pairs(d, S[u]) for d in ds)) // 2

  used[u] = True
  
print(ans)
  
0