結果

問題 No.439 チワワのなる木
ユーザー ikdikd
提出日時 2017-11-24 15:56:56
言語 D
(dmd 2.106.1)
結果
AC  
実行時間 142 ms / 5,000 ms
コード長 1,098 bytes
コンパイル時間 525 ms
コンパイル使用メモリ 89,064 KB
実行使用メモリ 33,028 KB
最終ジャッジ日時 2023-09-03 16:59:39
合計ジャッジ時間 2,615 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 1 ms
4,376 KB
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 1 ms
4,380 KB
testcase_05 AC 1 ms
4,376 KB
testcase_06 AC 1 ms
4,376 KB
testcase_07 AC 1 ms
4,376 KB
testcase_08 AC 1 ms
4,380 KB
testcase_09 AC 2 ms
4,384 KB
testcase_10 AC 1 ms
4,380 KB
testcase_11 AC 1 ms
4,376 KB
testcase_12 AC 1 ms
4,376 KB
testcase_13 AC 1 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,376 KB
testcase_17 AC 3 ms
4,376 KB
testcase_18 AC 85 ms
13,908 KB
testcase_19 AC 79 ms
13,388 KB
testcase_20 AC 114 ms
14,864 KB
testcase_21 AC 34 ms
7,708 KB
testcase_22 AC 31 ms
5,464 KB
testcase_23 AC 136 ms
16,068 KB
testcase_24 AC 142 ms
30,048 KB
testcase_25 AC 107 ms
15,820 KB
testcase_26 AC 95 ms
15,132 KB
testcase_27 AC 106 ms
33,028 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;
  void dfs2(int i, int pre=-1, long c=0, long w=0){
    if(s[i]=='w'){
      sum+=_c[i]*w+c*(_w[i]-1);
      foreach(j; g[i])if(j!=pre){
        sum+=_c[j]*(_w[i]-_w[j]-1);
      }
    }
    foreach(j; g[i])if(j!=pre){
      dfs2(j, i, c+(_c[i]-_c[j]), w+(_w[i]-_w[j]));
    }
  }

  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