結果

問題 No.439 チワワのなる木
ユーザー mkawa2mkawa2
提出日時 2020-04-25 01:01:35
言語 Python3
(3.11.6 + numpy 1.26.0 + scipy 1.11.3)
結果
AC  
実行時間 553 ms / 5,000 ms
コード長 1,792 bytes
コンパイル時間 161 ms
コンパイル使用メモリ 10,860 KB
実行使用メモリ 62,600 KB
最終ジャッジ日時 2023-08-05 06:23:06
合計ジャッジ時間 6,254 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 20 ms
8,868 KB
testcase_01 AC 19 ms
8,748 KB
testcase_02 AC 19 ms
8,820 KB
testcase_03 AC 20 ms
8,756 KB
testcase_04 AC 19 ms
8,760 KB
testcase_05 AC 19 ms
8,784 KB
testcase_06 AC 19 ms
8,828 KB
testcase_07 AC 19 ms
8,672 KB
testcase_08 AC 20 ms
8,748 KB
testcase_09 AC 21 ms
8,676 KB
testcase_10 AC 20 ms
8,676 KB
testcase_11 AC 19 ms
8,672 KB
testcase_12 AC 20 ms
8,748 KB
testcase_13 AC 20 ms
8,740 KB
testcase_14 AC 20 ms
8,928 KB
testcase_15 AC 23 ms
9,024 KB
testcase_16 AC 26 ms
9,248 KB
testcase_17 AC 25 ms
9,104 KB
testcase_18 AC 360 ms
26,416 KB
testcase_19 AC 294 ms
25,656 KB
testcase_20 AC 434 ms
31,924 KB
testcase_21 AC 118 ms
15,988 KB
testcase_22 AC 102 ms
14,908 KB
testcase_23 AC 506 ms
34,456 KB
testcase_24 AC 553 ms
48,636 KB
testcase_25 AC 418 ms
32,780 KB
testcase_26 AC 396 ms
31,172 KB
testcase_27 AC 406 ms
62,600 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from itertools import *
from bisect import *
from collections import *
from heapq import *
import sys

sys.setrecursionlimit(10 ** 6)

def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def SI(): return sys.stdin.readline()[:-1]
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]
int1 = lambda x: int(x) - 1
def MI1(): return map(int1, sys.stdin.readline().split())
def LI1(): return list(map(int1, sys.stdin.readline().split()))
p2D = lambda x: print(*x, sep="\n")
dij = [(1, 0), (0, 1), (-1, 0), (0, -1)]

def main():
    def dfs(u=0,pu=-1):
        for v in to[u]:
            if v==pu:continue
            dfs(v,u)
            w[u]+=w[v]+(s[v]=="w")*1
            ww[u]+=ww[v]+(s[v]=="w")*w[v]

    def dfs2(u=0,pu=-1):
        for v in to[u]:
            if v==pu:continue
            wv=w[v]+(s[v]=="w")*1
            ww[v]+=ww[u]-(ww[v]+(s[v]=="w")*w[v])+(w[u]-wv)*(s[u]=="w")
            w[v]+=w[u]-wv+(s[u]=="w")
            dfs2(v,u)


    n=II()
    s=SI()
    to=[[] for _ in range(n)]
    for _ in range(n-1):
        a,b=MI1()
        to[a].append(b)
        to[b].append(a)
    # 全方位DP
    # w[u]...頂点uのサブツリーのwの合計
    # ww[u]...頂点uのサブツリーのwwの合計
    w=[0]*n
    ww=[0]*n
    # 頂点0を根として子のサブツリーについて処理
    dfs()
    #print(w)
    #print(ww)
    # 親方向のサブツリーを加算していく
    dfs2()
    #print(w)
    #print(ww)
    # 文字がcの頂点におけるwwの数がcwwの数
    ans=0
    for u in range(n):
        if s[u]=="w":continue
        ans+=ww[u]
    print(ans)

main()
0