結果

問題 No.439 チワワのなる木
ユーザー ikdikd
提出日時 2017-11-24 11:59:59
言語 D
(dmd 2.105.2)
結果
AC  
実行時間 175 ms / 5,000 ms
コード長 1,216 bytes
コンパイル時間 588 ms
コンパイル使用メモリ 89,180 KB
実行使用メモリ 36,400 KB
最終ジャッジ日時 2023-09-03 16:59:14
合計ジャッジ時間 3,070 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 1 ms
4,376 KB
testcase_06 AC 1 ms
4,380 KB
testcase_07 AC 1 ms
4,380 KB
testcase_08 AC 1 ms
4,376 KB
testcase_09 AC 1 ms
4,376 KB
testcase_10 AC 1 ms
4,376 KB
testcase_11 AC 1 ms
4,376 KB
testcase_12 AC 1 ms
4,376 KB
testcase_13 AC 2 ms
4,376 KB
testcase_14 AC 2 ms
4,376 KB
testcase_15 AC 3 ms
4,376 KB
testcase_16 AC 3 ms
4,376 KB
testcase_17 AC 3 ms
4,384 KB
testcase_18 AC 106 ms
13,432 KB
testcase_19 AC 94 ms
14,940 KB
testcase_20 AC 141 ms
14,168 KB
testcase_21 AC 38 ms
9,528 KB
testcase_22 AC 34 ms
6,684 KB
testcase_23 AC 156 ms
16,464 KB
testcase_24 AC 175 ms
32,564 KB
testcase_25 AC 119 ms
15,636 KB
testcase_26 AC 111 ms
15,072 KB
testcase_27 AC 119 ms
36,400 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;
  import std.typecons;

  int n; rd(n);
  auto s=readln.chomp.to!(char[]);
  auto g=new int[][](n, 0);
  foreach(_; 0..(n-1)){
    int a, b; rd(a, b);
    g[a-1]~=(b-1);
    g[b-1]~=(a-1);
  }

  alias T=Tuple!(long, "w", long, "ww");
  auto _w=new long[](n), _ww=new long[](n);  
  T dfs(int i, int pre=-1){
    long w=0, ww=0;
    foreach(j; g[i])if(j!=pre){
      auto res=dfs(j, i);
      w+=res.w; ww+=res.ww;
    }
    if(s[i]=='w'){
      if(w>0) ww+=w;
      w++;
    }
    _w[i]=w; _ww[i]=ww;
    return T(w, ww);
  }

  long sum=0;
  void dfs2(int i, int pre=-1, long w=0, long ww=0){
    if(s[i]=='c') sum+=(_ww[i]+ww);
    // writeln(i, " ", sum, " ", _w[i], " ", _ww[i], " ", w, " ", ww);
    foreach(j; g[i])if(j!=pre){
      if(s[i]=='c') dfs2(j, i, w+(_w[i]-_w[j]), ww+(_ww[i]-_ww[j]));
      else dfs2(j, i, w+(_w[i]-_w[j]), ww+(_ww[i]-_ww[j])+(w-_w[j]));
    }
  }

  auto res=dfs(0);
  dfs2(0);
  writeln(sum);
  // writeln(_w);
  // writeln(_ww);
}


void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x){
    e=l[i].to!(typeof(e));
  }
}
0