結果

問題 No.439 チワワのなる木
ユーザー ikdikd
提出日時 2017-11-25 23:41:48
言語 D
(dmd 2.106.1)
結果
WA  
実行時間 -
コード長 1,164 bytes
コンパイル時間 2,334 ms
コンパイル使用メモリ 89,972 KB
実行使用メモリ 25,292 KB
最終ジャッジ日時 2023-09-03 17:04:46
合計ジャッジ時間 3,580 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 WA -
testcase_01 WA -
testcase_02 WA -
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 WA -
testcase_07 WA -
testcase_08 WA -
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 WA -
testcase_17 WA -
testcase_18 WA -
testcase_19 WA -
testcase_20 WA -
testcase_21 WA -
testcase_22 WA -
testcase_23 WA -
testcase_24 AC 155 ms
23,392 KB
testcase_25 WA -
testcase_26 WA -
testcase_27 WA -
権限があれば一括ダウンロードができます

ソースコード

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, "c", long, "w");
  auto _c=new long[](n), _w=new long[](n);
  T dfs(int i, int pre=-1){
    long c=0, w=0;
    foreach(j; g[i])if(j!=pre){
      auto res=dfs(j, i);
      c+=res.c; w+=res.w;
    }
    if(s[i]=='c') c++;
    if(s[i]=='w') w++;
    _c[i]=c; _w[i]=w;
    return T(c, w);
  }

  long sum=0;
  auto allw=reduce!((r, c)=>r+(c=='w'))(s);
  auto allc=reduce!((r, c)=>r+(c=='c'))(s);
  void dfs2(int i, int pre=-1){
    if(s[i]=='w'){
      sum+=_c[i]*(allw-_w[i]);
      sum+=(allc-_c[i])*(_w[i]-1);
      foreach(j; g[i])if(j!=pre){
        sum+=_w[j]*(_c[i]-_c[j]);
      }
    }
    foreach(j; g[i])if(j!=pre){
      dfs2(j, i);
    }
  }

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


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