結果

問題 No.439 チワワのなる木
ユーザー t8m8⛄️
提出日時 2016-11-01 17:30:27
言語 Nim
(2.2.0)
結果
AC  
実行時間 100 ms / 5,000 ms
コード長 713 bytes
コンパイル時間 3,359 ms
コンパイル使用メモリ 66,248 KB
実行使用メモリ 25,088 KB
最終ジャッジ日時 2024-06-29 19:55:31
合計ジャッジ時間 4,961 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 28
権限があれば一括ダウンロードができます

ソースコード

diff #

{.checks: off, optimization: speed.}

import strutils, sequtils

var
  n = stdin.readline.parseint
  s = stdin.readline
  g = newSeqWith(n, newSeq[int]())

for i in 0..n-2:
  var
    tmp = stdin.readline.split.map(parseint)
    (a, b) = (tmp[0]-1, tmp[1]-1)
  g[a].add(b)
  g[b].add(a)

var
  c = newSeq[int64](n)
  w = newSeq[int64](n)
  cAll = s.count('c')
  wAll = s.count('w')

proc dfs(cur, prev: int): int64 =
  if s[cur] == 'c': c[cur] = 1
  else: w[cur] = 1
  for i in g[cur]:
    if i == prev: continue
    result += dfs(i, cur)
    c[cur] += c[i]
    w[cur] += w[i]
    if s[cur] == 'w': result += c[i]*(wAll-1-w[i])
  if prev != -1 and s[cur] == 'w': result += (cAll-c[cur])*(w[cur]-1)

dfs(0, -1).echo
0