結果
| 問題 | No.1418 Sum of Sum of Subtree Size | 
| コンテスト | |
| ユーザー |  | 
| 提出日時 | 2021-03-05 21:40:52 | 
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 62 ms / 2,000 ms | 
| コード長 | 1,631 bytes | 
| コンパイル時間 | 777 ms | 
| コンパイル使用メモリ | 77,172 KB | 
| 最終ジャッジ日時 | 2025-01-19 10:45:47 | 
| ジャッジサーバーID (参考情報) | judge5 / judge4 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 41 | 
ソースコード
#line 2 "/Users/tiramister/CompetitiveProgramming/Cpp/CppLibrary/Graph/graph.hpp"
#include <vector>
template <class Cost = int>
struct Edge {
    int src, dst;
    Cost cost;
    Edge() = default;
    Edge(int src, int dst, Cost cost = 1)
        : src(src), dst(dst), cost(cost){};
    bool operator<(const Edge<Cost>& e) const { return cost < e.cost; }
    bool operator>(const Edge<Cost>& e) const { return cost > e.cost; }
};
template <class Cost = int>
struct Graph : public std::vector<std::vector<Edge<Cost>>> {
    using std::vector<std::vector<Edge<Cost>>>::vector;
    void span(bool direct, int src, int dst, Cost cost = 1) {
        (*this)[src].emplace_back(src, dst, cost);
        if (!direct) (*this)[dst].emplace_back(dst, src, cost);
    }
};
#line 2 "main.cpp"
#include <iostream>
#line 4 "main.cpp"
using namespace std;
using lint = long long;
void solve() {
    int n;
    cin >> n;
    Graph<> graph(n);
    for (int i = n - 1; i--;) {
        int u, v;
        cin >> u >> v;
        graph.span(false, --u, --v);
    }
    lint ans = 0;
    auto dfs = [&](auto&& f, int v, int p) -> lint {
        vector<lint> cz;
        lint sz = 1;
        for (auto e : graph[v]) {
            int u = e.dst;
            if (u == p) continue;
            lint c = f(f, u, v);
            cz.push_back(c);
            sz += c;
        }
        cz.push_back(n - sz);
        ans += n;
        for (auto c : cz) ans += c * (n - c);
        return sz;
    };
    dfs(dfs, 0, -1);
    cout << ans << "\n";
}
int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    solve();
    return 0;
}
            
            
            
        