結果

問題 No.439 チワワのなる木
ユーザー H3PO4H3PO4
提出日時 2021-07-10 09:35:47
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 593 ms / 5,000 ms
コード長 984 bytes
コンパイル時間 79 ms
コンパイル使用メモリ 10,892 KB
実行使用メモリ 35,300 KB
最終ジャッジ日時 2023-09-14 18:44:02
合計ジャッジ時間 6,046 ms
ジャッジサーバーID
(参考情報)
judge14 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 19 ms
8,572 KB
testcase_01 AC 19 ms
8,692 KB
testcase_02 AC 19 ms
8,568 KB
testcase_03 AC 19 ms
8,676 KB
testcase_04 AC 20 ms
8,616 KB
testcase_05 AC 19 ms
8,632 KB
testcase_06 AC 20 ms
8,448 KB
testcase_07 AC 19 ms
8,504 KB
testcase_08 AC 19 ms
8,600 KB
testcase_09 AC 20 ms
8,652 KB
testcase_10 AC 20 ms
8,516 KB
testcase_11 AC 19 ms
8,576 KB
testcase_12 AC 20 ms
8,584 KB
testcase_13 AC 20 ms
8,656 KB
testcase_14 AC 21 ms
8,724 KB
testcase_15 AC 24 ms
8,736 KB
testcase_16 AC 27 ms
9,040 KB
testcase_17 AC 24 ms
8,724 KB
testcase_18 AC 416 ms
23,568 KB
testcase_19 AC 389 ms
22,856 KB
testcase_20 AC 548 ms
27,824 KB
testcase_21 AC 162 ms
14,896 KB
testcase_22 AC 141 ms
13,960 KB
testcase_23 AC 593 ms
29,780 KB
testcase_24 AC 566 ms
31,772 KB
testcase_25 AC 551 ms
28,696 KB
testcase_26 AC 511 ms
27,836 KB
testcase_27 AC 394 ms
35,300 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import deque

input = sys.stdin.readline

N = int(input())
S = input()
T = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = (int(x) - 1 for x in input().split())
    T[a].append(b)
    T[b].append(a)

# dfs
dfs_order = []
parent = [None] * N
d = deque([0])
nonvisited = [True] * N
nonvisited[0] = False
while d:
    v = d.pop()
    dfs_order.append(v)
    for x in T[v]:
        if nonvisited[x]:
            d.append(x)
            parent[x] = v
            nonvisited[x] = False

Csum, Wsum = S.count('c'), S.count('w')

# 子から親へ
C, W = [0] * N, [0] * N
ans = 0
for v in reversed(dfs_order):
    if S[v] == 'c':
        C[v] += 1
    else:  # S[v] == 'w'
        W[v] += 1
    for child in T[v]:
        if child == parent[v]:
            continue
        C[v] += C[child]
        W[v] += W[child]
        if S[v] == 'w':
            ans += W[child] * (Csum - C[child])
    if S[v] == 'w':
        ans += C[v] * (Wsum - W[v])
print(ans)
0