8000 Update 1967_1.cpp · Getbra1n/basic-algo-lecture@0b4dffa · GitHub
[go: up one dir, main page]

Skip to content

Commit 0b4dffa

Browse files
Update 1967_1.cpp
1 parent d8b0621 commit 0b4dffa

File tree

1 file changed

+28
-23
lines changed

1 file changed

+28
-23
lines changed

0x19/solutions/1967_1.cpp

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,35 @@
11
// Authored by : syoh0708
2-
// Co-authored by : -
3-
// http://boj.kr/506e6d8e06d4409c9f52188587ce06f8
2+
// Co-authored by : BaaaaaaaaaaarkingDog
3+
// http://boj.kr/c50bcbc8af2f4462869639fe0f5b17da
44
#include <bits/stdc++.h>
5-
65
using namespace std;
76

87
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+
}
1828
}
29+
// 설령 자식이 1명이라도 second에 0이 들어있어 처리가 자연스럽게 가능
30+
diam = max(diam, first + second);
1931

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;
2633
}
2734

2835
int main() {
@@ -34,16 +41,14 @@ int main() {
3441
for (int i = 0; i < n - 1; i++) {
3542
int u, v, d; cin >> u >> v >> d;
3643

37-
e[u].push_back({v, d});
44+
adj[u].push_back({v, d});
3845
}
3946

4047
dfs(1);
41-
4248
cout << diam;
4349
}
4450

4551
/**
46-
* 트리의 지름을 그렸을 때 가장 루트에 가까운 노드를 a라 하자(문제의 예제에서 3번 노드)
47-
* 노드 a 입장에서 봤을 때 a의 자식 노드 c_i에 대해서 a에서 c_i를 지나는 리프까지의 최대 거리를 d_i라고 하면
48-
* 트리의 지름은 d_i 중 가장 긴 원소와 과 두 번째로 긴 원소를 더한 것과 같다.
52+
* 각 정점 x를 루트로 잡고 최대한 길게 내려가는 두 양갈래 정점 a, b를 구하고나면
53+
* a -> x -> b를 트리의 지름 후보로 생각할 수 있다. 이를 재귀적으로 구하면 된다.
4954
*/

0 commit comments

Comments
 (0)
0