본문 바로가기

알고리즘

트리의 최대 지름

트리 노드간의 최대 지름을 구하는 방법은 간단하다


1. 먼저 임의의 노드를 하나 선택한다음 최대거리의 노드를 구한다

2. 구한 노드를 다시 선택하여 그 노드의 최대거리가 트리에서 얻을수 있는 제일긴 노드간의 거리이다.


코드 - 백준 1167 트리의 지름 https://www.acmicpc.net/problem/1167


#include 
#include 
using namespace std;

#define sync() { ios_base::sync_with_stdio(0); cin.tie(0);}
#define endl '\n'

struct Edge { int to, weight; };
vector> graph;
vector visit;

int res, idx;

void dfs(int i, int x) {
    if (x > res) {
        res = x;
        idx = i;
    }
    visit[i] = 1;
    for (const auto &p : graph[i]) {
        if (not visit[p.to])
            dfs(p.to, x + p.weight);
    }
}

int main() {
    sync();

    int V;
    cin >> V;
    graph.resize(V+1);

    for(int i=0; i> e;
        while(true) {
            cin >> to;
            if (to == -1)
                break;
            cin >> weight;
            graph[e].push_back(Edge{to, weight});
        }
    }

    res = 0;
    visit.resize(V+1, 0);
    dfs(1, 0);
    fill(visit.begin(), visit.end(), 0);
    dfs(idx, 0);

    cout << res << endl;

    return 0;
}


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

LIS 최장 증가 수열  (0) 2017.11.15
펜윅트리로 최소값구하기  (0) 2017.08.25
알고리즘 기본지식  (0) 2016.11.24
소수 구하기  (0) 2016.11.19
멱집합 구하기  (0) 2016.11.17