結果

問題 No.439 チワワのなる木
ユーザー ikd
提出日時 2017-11-24 16:45:10
言語 D
(dmd 2.109.1)
結果
AC  
実行時間 139 ms / 5,000 ms
コード長 1,096 bytes
コンパイル時間 614 ms
コンパイル使用メモリ 103,764 KB
実行使用メモリ 32,644 KB
最終ジャッジ日時 2024-06-12 22:37:09
合計ジャッジ時間 2,447 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 28
権限があれば一括ダウンロードができます

ソースコード

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+=_w[j]*(_c[i]-_c[j]);
      }
    }
    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