結果

問題 No.439 チワワのなる木
ユーザー tktk_snsn
提出日時 2021-01-04 05:42:24
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 262 ms / 5,000 ms
コード長 867 bytes
コンパイル時間 180 ms
コンパイル使用メモリ 82,432 KB
実行使用メモリ 105,600 KB
最終ジャッジ日時 2024-10-14 01:25:02
合計ジャッジ時間 4,654 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 28
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import Counter
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

N = int(input())
S = input()
cnt = Counter(S)
G = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    G[a].append(b)
    G[b].append(a)

topo = []
par = [-1] * N
que = [0]
while que:
    s = que.pop()
    topo.append(s)
    for t in G[s]:
        if t == par[s]:
            continue
        G[t].remove(s)
        par[t] = s
        que.append(t)

ans = 0
C = [0] * N
W = [0] * N
for i in topo[::-1][:-1]:
    p = par[i]
    if S[i] == "w":
        c = cnt["c"] - C[i]
        w = W[i]
        ans += c * w
    if S[p] == "w":
        c = C[i] + (S[i] == "c")
        w = cnt["w"] - W[i] - 1 - (S[i] == "w")
        ans += c * w
    C[p] += C[i] + (S[i] == "c")
    W[p] += W[i] + (S[i] == "w")


print(ans)
0