結果
| 問題 | 
                            No.439 チワワのなる木
                             | 
                    
| コンテスト | |
| ユーザー | 
                             okaduki
                         | 
                    
| 提出日時 | 2017-12-09 01:11:30 | 
| 言語 | PyPy3  (7.3.15)  | 
                    
| 結果 | 
                             
                                AC
                                 
                             
                            
                         | 
                    
| 実行時間 | 506 ms / 5,000 ms | 
| コード長 | 769 bytes | 
| コンパイル時間 | 1,716 ms | 
| コンパイル使用メモリ | 82,192 KB | 
| 実行使用メモリ | 189,440 KB | 
| 最終ジャッジ日時 | 2024-11-29 20:29:53 | 
| 合計ジャッジ時間 | 5,454 ms | 
| 
                            ジャッジサーバーID (参考情報)  | 
                        judge5 / judge3 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| other | AC * 28 | 
ソースコード
import sys
sys.setrecursionlimit(1000000)
lines = sys.stdin.read().splitlines()
n = int(lines[0])
s = lines[1]
G = [[] for _ in range(n)]
for m in range(n-1):
    x, y = [int(i) for i in lines[2+m].split()]
    x -= 1
    y -= 1
    G[x].append(y)
    G[y].append(x)
nc = s.count('c')
nw = s.count('w')
dp1 = [[0,0] for _ in range(n)]
def dfs1(u, p):
    dp1[u][0] = 1 if s[u] == 'c' else 0
    dp1[u][1] = 1 if s[u] == 'w' else 0
    res = 0
    for to in G[u]:
        if to == p: continue
        res += dfs1(to, u)
        dp1[u][0] += dp1[to][0]
        dp1[u][1] += dp1[to][1]
        if s[u] == 'w':
            res += dp1[to][0] * (nw - dp1[to][1] - 1)
    if s[u] == 'w':
        res += (nc - dp1[u][0]) * (dp1[u][1] - 1)
    return res
print(dfs1(0,-1))
            
            
            
        
            
okaduki