1
1
// Authored by : syoh0708
2
- // Co-authored by : -
3
- // http://boj.kr/506e6d8e06d4409c9f52188587ce06f8
2
+ // Co-authored by : BaaaaaaaaaaarkingDog
3
+ // http://boj.kr/c50bcbc8af2f4462869639fe0f5b17da
4
4
#include < bits/stdc++.h>
5
-
6
5
using namespace std ;
7
6
8
7
int n, diam;
9
- vector<pair<int , int >> e[10005 ];
10
-
11
- pair<int , int > dfs (int cur) {
12
- int x = 0 , y = 0 ;
13
- vector<int > dist;
14
-
15
- for (auto nxt : e[cur]) {
16
- pair<int , int > d = dfs (nxt.first );
17
- dist.push_back (d.first + nxt.second );
8
+ vector<pair<int , int >> adj[10005 ];
9
+
10
+ // cur의 subtree에서 cur와 가장 거리가 먼 정점까지의 거리
11
+ int dfs (int cur) {
12
+ vector<int > dist;
13
+
14
+ int first = 0 ; // cur를 root로 하는 subtree에 속한 정점 중 cur와 가장 거리가 먼 정점까지의 거리
15
+ int second = 0 ; // cur를 root로 하는 subtree에 속한 정점 중 cur와 두번째로 먼 정점까지의 거리
16
+ // first + second가 트리의 지름 후보임
17
+
18
+ for (auto nxt : adj[cur]) {
19
+ // dist : cur의 자식인 nxt을 root로 하는 subtree에 있는 정점 중 cur와 가장 거리가 먼 정점까지의 거리
20
+ int dist = dfs (nxt.first ) + nxt.second ;
21
+ if (dist > first){ // 제일 긴게 갱신된다면
22
+ second = first;
23
+ first = dist;
24
+ }
25
+ else if (dist > second){ // 두번째로 긴게 갱신된다면
26
+ second = dist;
27
+ }
18
28
}
29
+ // 설령 자식이 1명이라도 second에 0이 들어있어 처리가 자연스럽게 가능
30
+ diam = max (diam, first + second);
19
31
20
- sort (dist.begin (), dist.end (), greater<int >());
21
- if (dist.size () > 0 ) x = dist[0 ];
22
- if (dist.size () > 1 ) y = dist[1 ];
23
- diam = max (diam, x + y);
24
-
25
- return {x, y};
32
+ return first;
26
33
}
27
34
28
35
int main () {
@@ -34,16 +41,14 @@ int main() {
34
41
for (int i = 0 ; i < n - 1 ; i++) {
35
42
int u, v, d; cin >> u >> v >> d;
36
43
37
- e [u].push_back ({v, d});
44
+ adj [u].push_back ({v, d});
38
45
}
39
46
40
47
dfs (1 );
41
-
42
48
cout << diam;
43
49
}
44
50
45
51
/* *
46
- * 트리의 지름을 그렸을 때 가장 루트에 가까운 노드를 a라 하자(문제의 예제에서 3번 노드)
47
- * 노드 a 입장에서 봤을 때 a의 자식 노드 c_i에 대해서 a에서 c_i를 지나는 리프까지의 최대 거리를 d_i라고 하면
48
- * 트리의 지름은 d_i 중 가장 긴 원소와 과 두 번째로 긴 원소를 더한 것과 같다.
52
+ * 각 정점 x를 루트로 잡고 최대한 길게 내려가는 두 양갈래 정점 a, b를 구하고나면
53
+ * a -> x -> b를 트리의 지름 후보로 생각할 수 있다. 이를 재귀적으로 구하면 된다.
49
54
*/
0 commit comments