結果

問題 No.439 チワワのなる木
ユーザー ふーらくたるふーらくたる
提出日時 2018-01-14 15:43:01
言語 C++14
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 86 ms / 5,000 ms
コード長 1,071 bytes
コンパイル時間 563 ms
コンパイル使用メモリ 70,224 KB
実行使用メモリ 21,468 KB
最終ジャッジ日時 2023-08-25 17:21:54
合計ジャッジ時間 2,346 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
5,684 KB
testcase_01 AC 3 ms
5,700 KB
testcase_02 AC 3 ms
5,712 KB
testcase_03 AC 3 ms
5,756 KB
testcase_04 AC 3 ms
5,692 KB
testcase_05 AC 3 ms
5,732 KB
testcase_06 AC 2 ms
5,744 KB
testcase_07 AC 3 ms
5,752 KB
testcase_08 AC 3 ms
5,892 KB
testcase_09 AC 3 ms
5,696 KB
testcase_10 AC 2 ms
5,688 KB
testcase_11 AC 3 ms
5,748 KB
testcase_12 AC 3 ms
5,692 KB
testcase_13 AC 3 ms
5,760 KB
testcase_14 AC 3 ms
5,708 KB
testcase_15 AC 4 ms
5,764 KB
testcase_16 AC 4 ms
5,800 KB
testcase_17 AC 3 ms
5,776 KB
testcase_18 AC 54 ms
9,224 KB
testcase_19 AC 50 ms
9,156 KB
testcase_20 AC 74 ms
10,264 KB
testcase_21 AC 24 ms
7,184 KB
testcase_22 AC 20 ms
6,932 KB
testcase_23 AC 86 ms
11,552 KB
testcase_24 AC 85 ms
19,768 KB
testcase_25 AC 66 ms
10,204 KB
testcase_26 AC 65 ms
10,596 KB
testcase_27 AC 75 ms
21,468 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
using namespace std;

using int64 = long long;

const int MAX_N = 100000;

vector<int> T[MAX_N];
int64 c[MAX_N], w[MAX_N];

int N;
string S;

int64 allc = 0, allw = 0;

int64 dfs(int v, int par) {
    if (S[v] == 'c') c[v]++;
    else w[v]++;

    int64 ans = 0, add = 0;
    int64 cumc = 0, cumw = 0;

    for (int to : T[v]) {
        if (to == par) continue;
        ans += dfs(to, v);
        c[v] += c[to];
        w[v] += w[to];

        cumc += c[to]; cumw += w[to];
        add -= c[to] * w[to];
    }
    int64 upc = allc - c[v],
          upw = allw - w[v];
    cumc += upc; cumw += upw;
    add -= upc * upw;
    add += cumc * cumw;

    if (S[v] != 'w') add = 0;
    ans += add;

    return ans;
}

int main() {
    cin >> N >> S;

    for (char ch : S) {
        if (ch == 'c') allc++;
        else allw++;
    }

    for (int i = 0; i < N - 1; i++) {
        int a, b;
        cin >> a >> b;
        a--; b--;
        T[a].push_back(b);
        T[b].push_back(a);
    }

    cout << dfs(0, -1) << endl;

    return 0;
}
0