結果

問題 No.439 チワワのなる木
ユーザー mayoko_mayoko_
提出日時 2016-04-26 08:42:36
言語 C++14
(gcc 12.3.0 + boost 1.83.0)
結果
WA  
実行時間 -
コード長 1,969 bytes
コンパイル時間 1,574 ms
コンパイル使用メモリ 172,784 KB
実行使用メモリ 6,948 KB
最終ジャッジ日時 2024-04-15 04:33:04
合計ジャッジ時間 3,455 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

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

ソースコード

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;
typedef pair<ll, ll> pll;

const ll mod = 1e9 + 7;

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

int dfs(int v, int p) {
    int ret = (s[v] == 'w');
    for (int ch : G[v]) if (ch != p) {
        ret += dfs(ch, v);
    }
    return ret;
}

struct UnionFind {
    vector<int> par;
    int n, cnt;
    UnionFind(const int& x = 0) {init(x);}
    void init(const int& x) {par.assign(cnt=n=x, -1);}
    inline int find(const int& x) {return par[x] < 0 ? x : par[x] = find(par[x]);}
    inline bool same(const int& x, const int& y) {return find(x) == find(y);}
    inline bool unite(int x, int y) {
        if ((x = find(x)) == (y = find(y))) return false;
        --cnt;
        if (par[x] > par[y]) swap(x, y);
        par[x] += par[y];
        par[y] = x;
        return true;
    }
    inline int count() const {return cnt;}
    inline int count(int x) {return -par[find(x)];}
};

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

    cin >> N;
    assert(3 <= N && N <= 2000);
    cin >> s;
    assert(N == s.size());
    for (int i = 0; i < N; i++) assert(s[i] == 'c' || s[i] == 'w');

    UnionFind uf(N);
    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);
        assert(a != b);
        assert(!uf.same(a, b));
        uf.unite(a, b);
    }
    assert(uf.count() == 1);
    // すべての c から木DP
    ll ans = 0;
    rep(i, N) {
        if (s[i] == 'c') {
            for (int ch : G[i]) {
                ll p = dfs(ch, i);
                ans += p*(p-1)/2;
            }
        }
    }
    cout << ans << endl;
}
0