結果

問題 No.439 チワワのなる木
ユーザー nebukuro09nebukuro09
提出日時 2017-04-04 17:17:17
言語 D
(dmd 2.107.1)
結果
AC  
実行時間 165 ms / 5,000 ms
コード長 1,409 bytes
コンパイル時間 948 ms
コンパイル使用メモリ 104,508 KB
実行使用メモリ 26,828 KB
最終ジャッジ日時 2023-09-03 12:40:48
合計ジャッジ時間 3,471 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,380 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,380 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,376 KB
testcase_10 AC 1 ms
4,376 KB
testcase_11 AC 1 ms
4,376 KB
testcase_12 AC 2 ms
4,376 KB
testcase_13 AC 2 ms
4,384 KB
testcase_14 AC 2 ms
4,376 KB
testcase_15 AC 2 ms
4,376 KB
testcase_16 AC 3 ms
4,380 KB
testcase_17 AC 3 ms
4,380 KB
testcase_18 AC 110 ms
13,904 KB
testcase_19 AC 100 ms
14,960 KB
testcase_20 AC 144 ms
14,164 KB
testcase_21 AC 41 ms
7,732 KB
testcase_22 AC 35 ms
5,412 KB
testcase_23 AC 159 ms
15,532 KB
testcase_24 AC 165 ms
24,700 KB
testcase_25 AC 126 ms
15,224 KB
testcase_26 AC 123 ms
14,900 KB
testcase_27 AC 117 ms
26,828 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop;

int N;
string S;
int[][] adj;
long allC, allW;
long[] subC, subW;


Tuple!(long, long) dfs1(int n, int prev) {
    subC[n] += (S[n] == 'c');
    subW[n] += (S[n] == 'w');
    foreach (m; adj[n]) {
        if (m == prev) continue;
        auto t = dfs1(m, n);
        subC[n] += t[0];
        subW[n] += t[1];
    }
    return tuple(subC[n], subW[n]);
}

long dfs2(int n, int prev) {
    long ret = 0;
    if (S[n] == 'w') {
        foreach (m; adj[n]) {
            if (m == prev) {
                auto c = allC - subC[n];
                auto w = subW[n] - 1;
                ret += c * w;
            }
            else {
                ret += subC[m] * (allW-subW[m]-1);
            }
        }
    }

    foreach (m; adj[n]) {
        if (m == prev) continue;
        ret += dfs2(m, n);
    }

    return ret;
}


void main() {
    N = readln.chomp.to!int;
    S = readln.chomp;
    adj = new int[][](N);
    foreach (i; 0..N-1) {
        auto s = readln.split.map!(to!int);
        adj[s[0]-1] ~= s[1] - 1;
        adj[s[1]-1] ~= s[0] - 1;
    }
    subC = new long[](N);
    subW = new long[](N);
    fill(subC, 0);
    fill(subW, 0);

    dfs1(0, -1);
    allC = subC[0];
    allW = subW[0];

    dfs2(0, -1).writeln;
}
0