8000 Create 1967_1.cpp · sms3025/basic-algo-lecture@d8b0621 · GitHub
[go: up one dir, main page]

Skip to content

Commit d8b0621

Browse files
committed
Create 1967_1.cpp
1 parent 3832232 commit d8b0621

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

0x19/solutions/1967_1.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Authored by : syoh0708
2+
// Co-authored by : -
3+
// http://boj.kr/506e6d8e06d4409c9f52188587ce06f8
4+
#include <bits/stdc++.h>
5+
6+
using namespace std;
7+
8+
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);
18+
}
19+
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};
26+
}
27+
28+
int main() {
29+
ios::sync_with_stdio(0);
30+
cin.tie(0);
31+
32+
cin >> n;
33+
34+
for (int i = 0; i < n - 1; i++) {
35+
int u, v, d; cin >> u >> v >> d;
36+
37+
e[u].push_back({v, d});
38+
}
39+
40+
dfs(1);
41+
42+
cout << diam;
43+
}
44+
45+
/**
46+
* 트리의 지름을 그렸을 때 가장 루트에 가까운 노드를 a라 하자(문제의 예제에서 3번 노드)
47+
* 노드 a 입장에서 봤을 때 a의 자식 노드 c_i에 대해서 a에서 c_i를 지나는 리프까지의 최대 거리를 d_i라고 하면
48+
* 트리의 지름은 d_i 중 가장 긴 원소와 과 두 번째로 긴 원소를 더한 것과 같다.
49+
*/

0 commit comments

Comments
 (0)
0