티스토리 뷰


전에  weeklyps 에서 트리의 지름을 공부할 배운 방법을 이용했다!

자세한 설명은 weeklyps에 있는 트리의 지름을 보는게 빠를듯.. ㅎㅎㅎ


정점 x를 기준으로 x의 서브트리에 속하는 최장거리, 안속하는 최장거리를 구해서 비교해주면 far 배열을 채울 수 있다..!


서브트리 속하는건 쉬워서 바로 구할 수 있다 트리의 깊이를 구하듯이 구하면 된다


속하지 않는 경우에는 다시 또 경우를 나눠서 구하면 된다...!

자세한 설명은 weeklyps 꼭 가보시길..! 저도 3번읽음 ㅎㅎ

다들 열공~~!


소스코드

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
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
#define MAXN 50050
bool check[MAXN];
int dist[MAXN], dist2[MAXN], far[MAXN],n;
vector<vector<pair<intint>>> Graph;
 
void dist_dfs(int x) {
    check[x] = true;
    dist[x] = dist2[x] = 0;
    for (int i = 0; i < Graph[x].size(); i++) {
        int next = Graph[x][i].first;
        int cost = Graph[x][i].second;
        if (check[next]) continue;
        dist_dfs(next);
        if (dist[x] < dist[next] + cost) {
            dist2[x] = dist[x];
            dist[x] = dist[next] + cost;
        }
        else if (dist2[x] < dist[next] + cost) dist2[x] = dist[next] + cost;
    }
}
void far_dfs(int x, int parent_far) {
    check[x] = true;
    far[x] = max(dist[x], parent_far);
    for (int i = 0; i < Graph[x].size(); i++) {
        int next = Graph[x][i].first;
        int cost = Graph[x][i].second;
        if (check[next]) continue;
        if (dist[x] == dist[next] + cost) far_dfs(next, max(parent_far + cost, dist2[x]+cost));
        else far_dfs(next, max(parent_far + cost, dist[x] + cost));
    }
}
int main() {
    scanf(" %d"&n);
    Graph.resize(n);
    for (int i = 0; i < n-1; i++) {
        int u, v, w; scanf(" %d %d %d"&u, &v, &w);
        u--; v--;
        Graph[u].push_back({ v,w });
        Graph[v].push_back({ u,w });
    }
    dist_dfs(0);
    memset(check, 0sizeof(check));
    far_dfs(00);
    for (int i = 0; i < n; i++printf("%d\n", far[i]);
}
cs


'알고리즘 > BOJ' 카테고리의 다른 글

[백준] 13977 이항계수와 쿼리  (0) 2018.06.25
[백준] 11964 Fruit Feast  (5) 2018.06.25
[백준] 1280 나무심기  (0) 2018.06.24
[백준] 9426 중앙값 측정  (0) 2018.06.22
[백준] 5012 불만정렬  (2) 2018.06.22
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
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
글 보관함