結果
問題 |
No.3113 The farthest point
|
ユーザー |
|
提出日時 | 2025-04-20 18:15:52 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 197 ms / 2,000 ms |
コード長 | 1,213 bytes |
コンパイル時間 | 2,391 ms |
コンパイル使用メモリ | 200,112 KB |
実行使用メモリ | 18,148 KB |
最終ジャッジ日時 | 2025-04-20 18:15:59 |
合計ジャッジ時間 | 6,512 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 33 |
ソースコード
#include <bits/stdc++.h> using namespace std; using ll = long long; int N; vector<vector<pair<int,ll>>> adj; ll ans = 0; // 再帰 DFS: u から下の部分木を処理し、dp[u] を返す ll dfs(int u, int p){ // 子からの寄与 (dp[v]+w) を貯める ll best1 = 0, best2 = 0; for(auto &e: adj[u]){ int v = e.first; ll w = e.second; if(v == p) continue; ll contrib = dfs(v, u) + w; if(contrib <= 0) continue; // 負なら切り捨て // best1 ≥ best2 を維持 if(contrib >= best1){ best2 = best1; best1 = contrib; } else if(contrib > best2){ best2 = contrib; } } // u を通る経路の候補:子2本をつなぐパス ans = max(ans, best1 + best2); // u から上(親方向)への寄与は best1 のみ return best1; } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); cin >> N; adj.assign(N+1, {}); for(int i = 0; i < N-1; i++){ int u, v; ll w; cin >> u >> v >> w; adj[u].emplace_back(v, w); adj[v].emplace_back(u, w); } dfs(1, 0); cout << ans << "\n"; return 0; }