본문 바로가기

Algorithm

(C++) - 백준(BOJ)코딩 1967번 : 트리의 지름 답

반응형
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
int n, u, v, w;
struct Edge {
    int to;
    int cost;
    Edge(int to, int cost) : to(to), cost(cost) {
    }
};
vector<Edge> a[10001];
int c[10001];
int d[10001];
void bfs(int start) {
    memset(d, 0, sizeof(d));
    memset(c, 0, sizeof(c));
    queue<int> q;
    c[start] = 1;
    q.push(start);
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        for (int i = 0; i<a[x].size(); i++) {
            Edge &e = a[x][i];
            if (c[e.to] == 0) {
                d[e.to] = d[x] + e.cost;
                q.push(e.to);
                c[e.to] = 1;
            }
        }
    }
}
int main() {
    
    cin >> n;
    for (int i = 0; i < n-1; i++) {
        cin >> u >> v >> w;
        a[u].push_back(Edge(v, w));
        a[v].push_back(Edge(u, w));
    }
    bfs(1);
    int start = 1;
    for (int i = 2; i <= n; i++) {
        if (d[i] > d[start]) {
            start = i;
        }
    }
    bfs(start);
    int ans = d[1];
    for (int i = 2; i <= n; i++) {
        if (ans < d[i]) {
            ans = d[i];
        }
    }
    cout << ans;
}