From 401d633dbe7daff093d33ac076355716d0c65cbe Mon Sep 17 00:00:00 2001 From: Ryo Suzuki Date: Mon, 9 Jan 2023 13:48:13 +0900 Subject: [PATCH] update --- 39.md | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 39.md diff --git a/39.md b/39.md new file mode 100644 index 0000000..aa6930c --- /dev/null +++ b/39.md @@ -0,0 +1,66 @@ +# 039 - Tree Distance (★5) + +## 解答 + +```cpp +#include +#include +#include + +void DFS(const std::vector>& graph, int from, int prev, std::vector& dp) +{ + dp[from] = 1; + + for (const auto& to : graph[from]) + { + if (to != prev) + { + DFS(graph, to, from, dp); + + // 帰りがけ順で dp を更新 + dp[from] += dp[to]; + } + } +} + +int main() +{ + int N; + std::cin >> N; + + std::vector A(N - 1), B(N - 1); + std::vector> graph(N); + for (int i = 0; i < (N - 1); ++i) + { + std::cin >> A[i] >> B[i]; + --A[i]; --B[i]; + graph[A[i]].push_back(B[i]); + graph[B[i]].push_back(A[i]); + } + + std::vector visited(N); + + // 頂点 0 を根としたうえで, + // dp[i]: i を根とする部分木の頂点数 + std::vector dp(N); + + DFS(graph, 0, -1, dp); + + long long answer = 0; + + // すべての辺について + for (int i = 0; i < (N - 1); ++i) + { + // 注目してる辺で葉側のグループの頂点数 + const long long a = std::min(dp[A[i]], dp[B[i]]); + + // その反対側のグループの頂点数 + const long long b = (N - a); + + // 組み合わせの数を加算 + answer += (a * b); + } + + std::cout << answer << '\n'; +} +``` diff --git a/README.md b/README.md index c9dfbd6..29f0b36 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ C++17 標準ライブラリの機能を優先して使い、競技プログラ |030| | | | | |[036](https://atcoder.jp/contests/typical90/tasks/typical90_aj)|[Max Manhattan Distance](./036.md)|★5|[👨‍🏫](https://raw.githubusercontent.com/E869120/kyopro_educational_90/main/editorial/036.jpg) / [📝](https://github.com/E869120/kyopro_educational_90/blob/main/sol/036.cpp)|マンハッタン距離は 45 度回転| |[037](https://atcoder.jp/contests/typical90/tasks/typical90_ak)|[Don't Leave the Spice](./037.md)|★5|[👨‍🏫](https://raw.githubusercontent.com/E869120/kyopro_educational_90/main/editorial/037.jpg) / [📝](https://github.com/E869120/kyopro_educational_90/blob/main/sol/037.cpp)|DP をセグメント木で高速化| -|039| | | | | +|[039](https://atcoder.jp/contests/typical90/tasks/typical90_am)|[Tree Distance](./039.md)|★5|[👨‍🏫](https://raw.githubusercontent.com/E869120/kyopro_educational_90/main/editorial/039.jpg) / [📝](https://github.com/E869120/kyopro_educational_90/blob/main/sol/039.cpp)|答えへの貢献度を考える| |051| | | | | |056| | | | | |[060](https://atcoder.jp/contests/typical90/tasks/typical90_bh)|[Chimera](./060.md)|★5|[👨‍🏫](https://raw.githubusercontent.com/E869120/kyopro_educational_90/main/editorial/060.jpg) / [📝](https://github.com/E869120/kyopro_educational_90/blob/main/sol/060.cpp)|両側から考える / 最長増加部分列|