結果

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

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 3 ms
5,740 KB
testcase_01 AC 3 ms
5,980 KB
testcase_02 AC 2 ms
5,700 KB
testcase_03 AC 2 ms
5,748 KB
testcase_04 AC 2 ms
5,816 KB
testcase_05 AC 2 ms
5,744 KB
testcase_06 AC 2 ms
5,752 KB
testcase_07 AC 2 ms
5,752 KB
testcase_08 AC 3 ms
5,724 KB
testcase_09 AC 2 ms
6,012 KB
testcase_10 AC 3 ms
5,784 KB
testcase_11 AC 2 ms
5,700 KB
testcase_12 AC 2 ms
5,904 KB
testcase_13 AC 2 ms
5,728 KB
testcase_14 AC 2 ms
5,728 KB
testcase_15 AC 3 ms
5,820 KB
testcase_16 AC 4 ms
5,796 KB
testcase_17 AC 4 ms
5,828 KB
testcase_18 AC 59 ms
9,504 KB
testcase_19 AC 55 ms
9,428 KB
testcase_20 AC 79 ms
10,588 KB
testcase_21 AC 23 ms
7,308 KB
testcase_22 AC 22 ms
7,076 KB
testcase_23 AC 91 ms
11,596 KB
testcase_24 AC 106 ms
16,140 KB
testcase_25 AC 73 ms
10,480 KB
testcase_26 AC 67 ms
11,052 KB
testcase_27 AC 75 ms
17,200 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 parent[MAX_N];

int N;
string S;

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

    parent[v] = par;

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

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

    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);
    }

    dfs(0, -1);

    int64 ans = 0;
    for (int v = 0; v < N; v++) {
        if (S[v] != 'w') continue;
        int64 upc = c[0] - c[v],
              upw = w[0] - w[v];
        int64 cumc = upc,
              cumw = upw;
        ans -= upc * upw;

        for (int to : T[v]) {
            if (to == parent[v]) continue;
            cumc += c[to];
            cumw += w[to];
            ans -= c[to] * w[to];
        }
        ans += cumc * cumw;
    }
    cout << ans << endl;

    return 0;
}
0