Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
Reputeless committed Jan 9, 2023
1 parent 45e24d6 commit 401d633
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
66 changes: 66 additions & 0 deletions 39.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# 039 - Tree Distance (★5)

## 解答

```cpp
#include <iostream>
#include <vector>
#include <algorithm>

void DFS(const std::vector<std::vector<int>>& graph, int from, int prev, std::vector<int>& 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<int> A(N - 1), B(N - 1);
std::vector<std::vector<int>> 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<bool> visited(N);

// 頂点 0 を根としたうえで,
// dp[i]: i を根とする部分木の頂点数
std::vector<int> 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';
}
```
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)|両側から考える / 最長増加部分列|
Expand Down

0 comments on commit 401d633

Please sign in to comment.