結果

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

ソースコード

diff #

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