結果

問題 No.439 チワワのなる木
ユーザー tktk_snsntktk_snsn
提出日時 2021-01-04 05:42:24
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 189 ms / 5,000 ms
コード長 867 bytes
コンパイル時間 165 ms
コンパイル使用メモリ 82,380 KB
実行使用メモリ 105,664 KB
最終ジャッジ日時 2024-04-22 02:41:57
合計ジャッジ時間 3,410 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 35 ms
54,860 KB
testcase_01 AC 36 ms
54,372 KB
testcase_02 AC 38 ms
54,416 KB
testcase_03 AC 36 ms
54,976 KB
testcase_04 AC 36 ms
56,296 KB
testcase_05 AC 42 ms
53,776 KB
testcase_06 AC 40 ms
54,248 KB
testcase_07 AC 41 ms
53,568 KB
testcase_08 AC 42 ms
54,492 KB
testcase_09 AC 42 ms
54,852 KB
testcase_10 AC 41 ms
54,992 KB
testcase_11 AC 39 ms
54,724 KB
testcase_12 AC 40 ms
54,744 KB
testcase_13 AC 41 ms
54,980 KB
testcase_14 AC 43 ms
56,300 KB
testcase_15 AC 59 ms
68,460 KB
testcase_16 AC 62 ms
72,160 KB
testcase_17 AC 57 ms
70,320 KB
testcase_18 AC 154 ms
91,720 KB
testcase_19 AC 136 ms
90,668 KB
testcase_20 AC 178 ms
97,376 KB
testcase_21 AC 95 ms
81,676 KB
testcase_22 AC 93 ms
81,612 KB
testcase_23 AC 189 ms
98,044 KB
testcase_24 AC 168 ms
97,544 KB
testcase_25 AC 162 ms
102,080 KB
testcase_26 AC 174 ms
105,664 KB
testcase_27 AC 111 ms
97,212 KB
権限があれば一括ダウンロードができます

ソースコード

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