結果

問題 No.439 チワワのなる木
ユーザー 🍡yurahuna🍡yurahuna
提出日時 2016-04-29 12:03:25
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,378 ms / 5,000 ms
コード長 1,070 bytes
コンパイル時間 261 ms
コンパイル使用メモリ 82,304 KB
実行使用メモリ 220,764 KB
最終ジャッジ日時 2024-04-15 12:45:39
合計ジャッジ時間 9,855 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 52 ms
53,504 KB
testcase_01 AC 52 ms
53,504 KB
testcase_02 AC 52 ms
53,632 KB
testcase_03 AC 55 ms
53,632 KB
testcase_04 AC 56 ms
53,760 KB
testcase_05 AC 58 ms
53,504 KB
testcase_06 AC 58 ms
53,760 KB
testcase_07 AC 52 ms
53,760 KB
testcase_08 AC 56 ms
54,016 KB
testcase_09 AC 55 ms
54,144 KB
testcase_10 AC 56 ms
54,272 KB
testcase_11 AC 55 ms
53,632 KB
testcase_12 AC 53 ms
53,760 KB
testcase_13 AC 59 ms
55,168 KB
testcase_14 AC 62 ms
56,064 KB
testcase_15 AC 116 ms
76,928 KB
testcase_16 AC 133 ms
77,184 KB
testcase_17 AC 126 ms
77,184 KB
testcase_18 AC 558 ms
96,384 KB
testcase_19 AC 498 ms
94,964 KB
testcase_20 AC 665 ms
102,420 KB
testcase_21 AC 303 ms
84,732 KB
testcase_22 AC 347 ms
84,224 KB
testcase_23 AC 1,100 ms
115,328 KB
testcase_24 AC 1,378 ms
207,796 KB
testcase_25 AC 400 ms
103,396 KB
testcase_26 AC 411 ms
104,320 KB
testcase_27 AC 804 ms
220,764 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict as ddict
import sys
sys.setrecursionlimit(1000000)

def dfs(v, par):
    ret = [0, 0]    # (ww, w)
    for ch in G[v]:
        if ch == par:
            continue
        child = dfs(ch, v)
        ret[0] += child[0]
        ret[1] += child[1]

    if s[v] == 'w':
        ret[0] += ret[1]
        ret[1] += 1

    C[v] = ret
    return ret

ans = 0
def dfs2(v, par, p):
    global ans
    if s[v] == 'c':
        ans += p[0]
        for ch in G[v]:
            if ch == par:
                continue
            ans += C[ch][0]

    for ch in G[v]:
        if ch == par:
            continue
        tmp = list(p)
        tmp[0] += C[v][0]; tmp[1] += C[v][1]
        tmp[0] -= C[ch][0]; tmp[1] -= C[ch][1]
        if s[v] == 'w':
            tmp[0] -= C[ch][1]
            tmp[0] += p[1]
        dfs2(ch, v, tmp)

N = int(input())
s = input()
G = ddict(list)
for i in range(N - 1):
    a, b = map(int, input().split())
    a -= 1; b -= 1
    G[a].append(b)
    G[b].append(a)

C = [None] * N
dfs(0, -1)
dfs2(0, -1, [0, 0])
print(ans)
0