結果

問題 No.3113 The farthest point
ユーザー テナガザル
提出日時 2025-04-19 02:42:50
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 342 ms / 2,000 ms
コード長 1,392 bytes
コンパイル時間 1,171 ms
コンパイル使用メモリ 108,548 KB
実行使用メモリ 16,832 KB
最終ジャッジ日時 2025-04-19 02:42:58
合計ジャッジ時間 7,519 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

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

using namespace std;

int main()
{
  int n;
  cin >> n;
  vector<vector<pair<int, int>>> g(n);
  for (int i = 1; i < n; ++i)
  {
    int u, v, w;
    cin >> u >> v >> w;
    --u, --v;
    g[u].emplace_back(v, w);
    g[v].emplace_back(u, w);
  }
  vector<long long> dis(n);
  auto dfs = [&](auto f, int now, int p) -> void
  {
    dis[now] = 0;
    for (auto [to, c] : g[now])
    {
      if (to == p) continue;
      f(f, to, now);
      dis[now] = max(dis[now], dis[to] + c);
    }
  };
  dfs(dfs, 0, -1);
  long long ans = 0;
  auto cal = [&](auto f, int now, int p, long long pd) -> void
  {
    pd = max(pd, 0LL);
    ans = max(ans, dis[now] + pd);
    int siz = g[now].size();
    vector<long long> l(siz, pd), r(siz, pd);
    for (int i = 0; i < siz - 1; ++i)
    {
      l[i + 1] = l[i];
      if (g[now][i].first == p) continue;
      l[i + 1] = max(l[i + 1], dis[g[now][i].first] + g[now][i].second);
    }
    for (int i = siz - 1; i > 0; --i)
    {
      r[i - 1] = r[i];
      if (g[now][i].first == p) continue;
      r[i - 1] = max(r[i - 1], dis[g[now][i].first] + g[now][i].second);
    }
    for (int i = 0; i < siz; ++i)
    {
      if (g[now][i].first == p) continue;
      f(f, g[now][i].first, now, max(l[i], r[i]) + g[now][i].second);
    }
  };
  cal(cal, 0, -1, 0);
  cout << ans << endl;
}
0