結果

問題 No.439 チワワのなる木
ユーザー 🍡yurahuna🍡yurahuna
提出日時 2016-04-29 00:42:57
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
TLE  
実行時間 -
コード長 1,409 bytes
コンパイル時間 1,786 ms
コンパイル使用メモリ 168,456 KB
実行使用メモリ 12,672 KB
最終ジャッジ日時 2024-04-19 07:35:41
合計ジャッジ時間 8,569 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
5,248 KB
testcase_01 AC 2 ms
5,376 KB
testcase_02 AC 2 ms
5,376 KB
testcase_03 AC 2 ms
5,376 KB
testcase_04 AC 2 ms
5,376 KB
testcase_05 AC 2 ms
5,376 KB
testcase_06 AC 2 ms
5,376 KB
testcase_07 AC 1 ms
5,376 KB
testcase_08 AC 1 ms
5,376 KB
testcase_09 AC 2 ms
5,376 KB
testcase_10 AC 2 ms
5,376 KB
testcase_11 AC 2 ms
5,376 KB
testcase_12 AC 2 ms
5,376 KB
testcase_13 AC 2 ms
5,376 KB
testcase_14 AC 3 ms
5,376 KB
testcase_15 AC 10 ms
5,376 KB
testcase_16 AC 44 ms
5,376 KB
testcase_17 AC 26 ms
5,376 KB
testcase_18 TLE -
testcase_19 -- -
testcase_20 -- -
testcase_21 -- -
testcase_22 -- -
testcase_23 -- -
testcase_24 -- -
testcase_25 -- -
testcase_26 -- -
testcase_27 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

#define rep(i,n) for (int i=0;i<(n);i++)
#define rep2(i,a,b) for (int i=(a);i<(b);i++)
#define rrep(i,n) for (int i=(n)-1;i>=0;i--)
#define rrep2(i,a,b) for (int i=(b)-1;i>=(a);i--)
#define all(a) (a).begin(),(a).end()

typedef long long ll;
typedef pair<int, int> P;

// O(N^2)解
// すべてのcから毎回木DPする

int N;
string s;
vector<vector<int>> G;

struct Chiwawa {
    int w, ww;
    Chiwawa() { w = 0; ww = 0; }
};

Chiwawa dfs(int now, int pre) {
    Chiwawa ret;

    for (auto nxt : G[now]) {
        if (nxt == pre) continue;
        auto child = dfs(nxt, now);
        ret.w += child.w;
        ret.ww += child.ww;
    }

    if (s[now] == 'w') {
        // 自分がwなら、子のwの数だけwwが増える
        ret.ww += ret.w;
        // wは1増える
        ++ret.w;
    }

    return ret;
}

signed main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(0);

    cin >> N;
    cin >> s;

    G.resize(N);
    rep(i, N - 1) {
        int a, b;
        cin >> a >> b;
        a--; b--;
        G[a].emplace_back(b);
        G[b].emplace_back(a);
    }


    // すべての c から木DP
    ll ans = 0;
    rep(i, N) {
        // このcからパスとしてとれるwwの数を足す
        if (s[i] == 'c') {
            auto ret = dfs(i, -1);
            ans += ret.ww;
        }
    }

    cout << ans << endl;

}
0