結果

問題 No.1769 Don't Stop the Game
ユーザー first_vil
提出日時 2021-10-22 16:23:09
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 816 ms / 3,000 ms
コード長 1,955 bytes
コンパイル時間 2,611 ms
コンパイル使用メモリ 213,896 KB
最終ジャッジ日時 2025-01-25 02:50:51
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 28
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int i=0;i<n;++i)

int main() {
    int n; cin >> n;
    vector<vector<pair<int, int>>> g(n);
    rep(i, n - 1) {
        int a, b, c; cin >> a >> b >> c;
        --a, --b;
        g[a].emplace_back(b, c);
        g[b].emplace_back(a, c);
    }

    vector<int> siz(n, 1), x(n);
    auto dfs0 = [&](auto&& f, int cur, int par)->void {
        for (auto [to, weight] : g[cur]) {
            if (to == par)continue;
            x[to] = x[cur] ^ weight;
            f(f, to, cur);
            siz[cur] += siz[to];
        }
    };
    dfs0(dfs0, 0, -1);
    auto sorted_x = x;
    sort(sorted_x.begin(), sorted_x.end());
    rep(i, n)x[i] = lower_bound(sorted_x.begin(), sorted_x.end(), x[i]) - sorted_x.begin();//compress

    ll ans = ll(n) * (n - 1);
    auto dfs1 = [&](auto&& f, int cur, int par)->map<int, pair<int, int>> {
        map<int, pair<int, int>> L;//{y,cnt}
        for (auto [to, weight] : g[cur]) {
            if (to == par)continue;
            auto R = f(f, to, cur);
            if (R.count(x[cur])) {
                ans -= ll(R[x[cur]].second) * (n - siz[to]);//case-2
                ans -= ll(R[x[cur]].first) * R[x[cur]].second;//case-3
            }
            if (L.size() > R.size())swap(L, R);
            for (auto [l_XOR, val] : L) {
                auto [y, cnt] = val;
                R[l_XOR].first += y;
                R[l_XOR].second += cnt;
            }
            swap(L, R);
        }
        if (L.count(x[cur])) {
            ans -= L[x[cur]].first;//case-1
        }
        L[x[cur]] = { siz[cur],1 };
        if (cur == 0) {
            for (auto [l_XOR, val] : L) {
                auto [y, cnt] = val;
                if (l_XOR != x[cur])ans -= ll(y) * cnt;//case-3
            }
        }
        else ans += siz[cur];//case-3
        return L;
    };
    dfs1(dfs1, 0, -1);
    cout << ans << "\n";

    return 0;
}
0