結果
| 問題 | No.1418 Sum of Sum of Subtree Size | 
| コンテスト | |
| ユーザー |  hitonanode | 
| 提出日時 | 2021-02-06 11:42:49 | 
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 102 ms / 2,000 ms | 
| コード長 | 849 bytes | 
| コンパイル時間 | 554 ms | 
| コンパイル使用メモリ | 71,020 KB | 
| 最終ジャッジ日時 | 2025-01-18 13:27:59 | 
| ジャッジサーバーID (参考情報) | judge2 / judge1 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 41 | 
ソースコード
#include <forward_list>
#include <iostream>
using namespace std;
forward_list<int> to[100000];
int main() {
    int N;
    cin >> N;
    for (int i = 0; i < N - 1; i++) {
        int a, b;
        cin >> a >> b;
        a--, b--;
        to[a].push_front(b);
        to[b].push_front(a);
    }
    long long ret = 1LL * N * N;
    auto f = [&N](long long x) -> long long { return x * (N - x); };
    auto dfs = [&](auto self, int now, int prv) -> int {
        int subtree_size = 1;
        for (auto nxt : to[now]) {
            if (nxt != prv) {
                int tmp = self(self, nxt, now);
                ret += f(tmp);
                subtree_size += tmp;
            }
        }
        ret += f(subtree_size);
        return subtree_size;
    };
    dfs(dfs, 0, -1);
    cout << ret << '\n';
}
            
            
            
        