結果
問題 | No.872 All Tree Path |
ユーザー |
|
提出日時 | 2020-04-21 20:34:49 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 204 ms / 3,000 ms |
コード長 | 1,804 bytes |
コンパイル時間 | 1,134 ms |
コンパイル使用メモリ | 90,688 KB |
最終ジャッジ日時 | 2025-01-09 22:08:02 |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 18 |
ソースコード
#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; }