結果

問題 No.872 All Tree Path
ユーザー MisterMister
提出日時 2020-04-21 20:34:49
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 142 ms / 3,000 ms
コード長 1,804 bytes
コンパイル時間 866 ms
コンパイル使用メモリ 94,364 KB
実行使用メモリ 37,632 KB
最終ジャッジ日時 2024-04-17 11:40:39
合計ジャッジ時間 3,660 ms
ジャッジサーバーID
(参考情報)
judge5 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 138 ms
19,584 KB
testcase_01 AC 142 ms
19,712 KB
testcase_02 AC 134 ms
19,712 KB
testcase_03 AC 97 ms
37,632 KB
testcase_04 AC 2 ms
5,376 KB
testcase_05 AC 137 ms
19,840 KB
testcase_06 AC 135 ms
19,712 KB
testcase_07 AC 127 ms
19,840 KB
testcase_08 AC 12 ms
5,376 KB
testcase_09 AC 11 ms
5,376 KB
testcase_10 AC 12 ms
5,376 KB
testcase_11 AC 12 ms
5,376 KB
testcase_12 AC 11 ms
5,376 KB
testcase_13 AC 1 ms
5,376 KB
testcase_14 AC 2 ms
5,376 KB
testcase_15 AC 2 ms
5,376 KB
testcase_16 AC 2 ms
5,376 KB
testcase_17 AC 2 ms
5,376 KB
testcase_18 AC 2 ms
5,376 KB
testcase_19 AC 2 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <functional>

template <class Cost = int>
struct Edge {
    int src, dst;
    Cost cost;
    Edge(int src = -1, int dst = -1, Cost cost = 1)
        : src(src), dst(dst), cost(cost){};

    bool operator<(const Edge<Cost>& e) const { return this->cost < e.cost; }
    bool operator>(const Edge<Cost>& e) const { return this->cost > e.cost; }
};

template <class Cost = int>
struct Graph {
    std::vector<std::vector<Edge<Cost>>> graph;

    Graph(int n = 0) : graph(n) {}

    void span(bool direct, int src, int dst, Cost cost = 1) {
        graph[src].emplace_back(src, dst, cost);
        if (!direct) graph[dst].emplace_back(dst, src, cost);
    }

    std::vector<Edge<Cost>>& operator[](int v) { return graph[v]; }
    std::vector<Edge<Cost>> operator[](int v) const { return graph[v]; }

    int size() const { return graph.size(); }
};

using lint = long long;

void solve() {
    int n;
    std::cin >> n;

    Graph<lint> graph(n);
    for (int i = 0; i < n - 1; ++i) {
        int u, v;
        lint d;
        std::cin >> u >> v >> d;
        graph.span(false, --u, --v, d);
    }

    std::vector<lint> szs(n, 1);
    std::function<void(int, int)> dfs =
        [&](int v, int p) {
            for (auto e : graph[v]) {
                int u = e.dst;
                if (u == p) continue;

                dfs(u, v);
                szs[v] += szs[u];
            }
        };

    dfs(0, -1);

    lint ans = 0;
    for (int v = 0; v < n; ++v) {
        for (auto e : graph[v]) {
            lint sz = std::min(szs[e.src], szs[e.dst]);
            ans += sz * (n - sz) * e.cost;
        }
    }

    std::cout << ans << std::endl;
}

int main() {
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);

    solve();

    return 0;
}
0