結果

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

ソースコード

diff #

#include <iostream>
#include <vector>
#include <climits>
#include <queue>
#include <algorithm>

using namespace std;
using ll = long long;
using P = pair<int, ll>;

int N;
vector<vector<P>> G;

pair<int, ll> bfs(int start) {
    vector<ll> dist(N + 1, LLONG_MIN);
    queue<int> q;
    dist[start] = 0;
    q.push(start);

    int far = start;
    while (!q.empty()) {
        int cur = q.front(); q.pop();
        for (auto [to, cost] : G[cur]) {
            if (dist[to] == LLONG_MIN) {
                dist[to] = dist[cur] + cost;
                q.push(to);
                if (dist[to] > dist[far]) {
                    far = to;
                }
            }
        }
    }
    return {far, dist[far]};
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> N;
    G.resize(N + 1);  // 1-indexed

    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回目のBFSで遠い点を見つける
    int farthest = bfs(1).first;
    // 2回目のBFSで直径を求める
    ll diameter = bfs(farthest).second;

    cout << diameter << '\n';
    return 0;
}
0