結果

問題 No.3113 The farthest point
ユーザー karashi-0086A2
提出日時 2025-04-20 19:25:33
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 879 bytes
コンパイル時間 2,016 ms
コンパイル使用メモリ 196,260 KB
実行使用メモリ 25,468 KB
最終ジャッジ日時 2025-04-20 19:25:42
合計ジャッジ時間 8,716 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 20 WA * 13
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<ll, int>;

const int MAXN = 500005;

vector<pair<int, ll>> G[MAXN];
int farthest_node;
ll max_dist;

void dfs(int v, int p, ll d) {
    if (d > max_dist) {
        max_dist = d;
        farthest_node = v;
    }
    for (auto [to, cost] : G[v]) {
        if (to == p) continue;
        dfs(to, v, d + cost);
    }
}

int main() {
    int N;
    cin >> N;
    for (int i = 0; i < N - 1; ++i) {
        int u, v;
        ll w;
        cin >> u >> v >> w;
        G[u].emplace_back(v, w);
        G[v].emplace_back(u, w);
    }

    // 1回目のDFSで最も遠い点Aを探す
    max_dist = -1;
    dfs(1, -1, 0);
    int A = farthest_node;

    // 2回目のDFSでAから最も遠い点Bまでの距離が直径
    max_dist = -1;
    dfs(A, -1, 0);

    cout << max_dist << endl;
    return 0;
}
0