結果

問題 No.439 チワワのなる木
ユーザー ikdikd
提出日時 2017-11-25 23:44:06
言語 D
(dmd 2.106.1)
結果
AC  
実行時間 160 ms / 5,000 ms
コード長 1,170 bytes
コンパイル時間 691 ms
コンパイル使用メモリ 89,628 KB
実行使用メモリ 25,260 KB
最終ジャッジ日時 2023-09-03 17:04:56
合計ジャッジ時間 3,139 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 2 ms
4,376 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 1 ms
4,376 KB
testcase_05 AC 1 ms
4,376 KB
testcase_06 AC 1 ms
4,384 KB
testcase_07 AC 1 ms
4,380 KB
testcase_08 AC 1 ms
4,380 KB
testcase_09 AC 1 ms
4,380 KB
testcase_10 AC 1 ms
4,376 KB
testcase_11 AC 1 ms
4,380 KB
testcase_12 AC 2 ms
4,384 KB
testcase_13 AC 2 ms
4,380 KB
testcase_14 AC 2 ms
4,380 KB
testcase_15 AC 3 ms
4,380 KB
testcase_16 AC 3 ms
4,380 KB
testcase_17 AC 3 ms
4,380 KB
testcase_18 AC 101 ms
13,368 KB
testcase_19 AC 92 ms
13,644 KB
testcase_20 AC 136 ms
14,160 KB
testcase_21 AC 38 ms
7,216 KB
testcase_22 AC 35 ms
6,952 KB
testcase_23 AC 150 ms
15,480 KB
testcase_24 AC 160 ms
23,428 KB
testcase_25 AC 120 ms
15,280 KB
testcase_26 AC 113 ms
14,996 KB
testcase_27 AC 112 ms
25,260 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, "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'))(0, s);
  auto allc=reduce!((r, c)=>r+(c=='c'))(0, 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