結果

問題 No.872 All Tree Path
ユーザー KKT89
提出日時 2024-01-31 12:22:00
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 181 ms / 3,000 ms
コード長 950 bytes
コンパイル時間 2,682 ms
コンパイル使用メモリ 218,428 KB
最終ジャッジ日時 2025-02-19 00:52:52
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 18
権限があれば一括ダウンロードができます

ソースコード

diff #

#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) { return (ull)rng() % B; }

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<vector<pair<int, ll>>> g(n);
    for (int i = 0; i < n - 1; i++) {
        int x, y, z;
        cin >> x >> y >> z;
        x -= 1, y -= 1;
        g[x].push_back({y, z});
        g[y].push_back({x, z});
    }
    ll res = 0;
    vector<ll> sz(n);
    auto dfs = [&](auto dfs, int s, int p) -> void {
        sz[s] = 1;
        for (auto to : g[s]) {
            int t = to.first;
            if (t == p) continue;
            dfs(dfs, t, s);
            res += to.second * (sz[t]) * (n - sz[t]);
            sz[s] += sz[t];
        }
    };
    dfs(dfs, 0, -1);
    cout << res*2 << endl;
}
0