File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
8000
1
+ // Authored by : syoh0708
2
+ // Co-authored by : BaaaaaaaaaaarkingDog
3
+ // http://boj.kr/c50bcbc8af2f4462869639fe0f5b17da
4
+ #include < bits/stdc++.h>
5
+ using namespace std ;
6
+
7
+ int n, diam;
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
+ }
28
+ }
29
+ // 설령 자식이 1명이라도 second에 0이 들어있어 처리가 자연스럽게 가능
30
+ diam = max (diam, first + second);
31
+
32
+ return first;
33
+ }
34
+
35
+ int main () {
36
+ ios::sync_with_stdio (0 );
37
+ cin.tie (0 );
38
+
39
+ cin >> n;
40
+
41
+ for (int i = 0 ; i < n - 1 ; i++) {
42
+ int u, v, d; cin >> u >> v >> d;
43
+
44
+ adj[u].push_back ({v, d});
45
+ }
46
+
47
+ dfs (1 );
48
+ cout << diam;
49
+ }
50
+
51
+ /* *
52
+ * 각 정점 x를 루트로 잡고 최대한 길게 내려가는 두 양갈래 정점 a, b를 구하고나면
53
+ * a -> x -> b를 트리의 지름 후보로 생각할 수 있다. 이를 재귀적으로 구하면 된다.
54
+ */
You can’t perform that action at this time.
0 commit comments