結果
問題 | No.1418 Sum of Sum of Subtree Size |
ユーザー | magsta |
提出日時 | 2021-03-05 21:46:32 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 87 ms / 2,000 ms |
コード長 | 1,194 bytes |
コンパイル時間 | 794 ms |
コンパイル使用メモリ | 74,316 KB |
実行使用メモリ | 20,352 KB |
最終ジャッジ日時 | 2024-10-07 01:20:03 |
合計ジャッジ時間 | 3,134 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 41 |
ソースコード
#include <iostream> #include <vector> using namespace std; using Graph = vector<vector<int>>; vector<long long> depth; vector<long long> subtree_size; vector<long long> count_; int N; void dfs(const Graph& G, int v, int p, int d) { depth[v] = d; for (auto nv : G[v]) { if (nv == p) continue; dfs(G, nv, v, d + 1); } subtree_size[v] = 1; for (auto c : G[v]) { if (c == p) continue; subtree_size[v] += subtree_size[c]; } } void dfs2(const Graph& G, int v, int p) { if (v != 0) count_[v] = count_[p] + N - 2 * subtree_size[v]; for (auto nv : G[v]) { if (nv == p) continue; dfs2(G, nv, v); } } int main() { cin >> N; Graph G(N); for (int i = 0; i < N - 1; i++) { int a, b; cin >> a >> b; G[a - 1].push_back(b - 1); G[b - 1].push_back(a - 1); } depth.assign(N, 0); subtree_size.assign(N, 0); count_.assign(N, 0); dfs(G, 0, -1, 0); for (int i = 0; i < N; i++) { count_[0] += subtree_size[i]; } dfs2(G, 0, -1); long long ans = 0; for (int i = 0; i < N; i++) { ans += count_[i]; } cout << ans << endl; }