-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy path039.cpp
More file actions
40 lines (35 loc) · 746 Bytes
/
039.cpp
File metadata and controls
40 lines (35 loc) · 746 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
long long N;
long long A[1 << 18], B[1 << 18];
long long dp[1 << 18];
vector<int> G[1 << 18];
void dfs(int pos, int pre) {
dp[pos] = 1;
for (int i : G[pos]) {
if (i == pre) continue;
dfs(i, pos);
dp[pos] += dp[i];
}
}
int main() {
// Step #1. 入力
cin >> N;
for (int i = 1; i <= N - 1; i++) {
cin >> A[i] >> B[i];
G[A[i]].push_back(B[i]);
G[B[i]].push_back(A[i]);
}
// Step #2. 深さ優先探索(DFS)
dfs(1, -1);
// Step #3. 答えを求める
long long Answer = 0;
for (int i = 1; i <= N - 1; i++) {
long long r = min(dp[A[i]], dp[B[i]]);
Answer += r * (N - r);
}
cout << Answer << endl;
return 0;
}