結果

問題 No.3113 The farthest point
ユーザー k1suxu
提出日時 2025-04-19 20:01:46
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 225 ms / 2,000 ms
コード長 2,578 bytes
コンパイル時間 4,002 ms
コンパイル使用メモリ 286,520 KB
実行使用メモリ 35,184 KB
最終ジャッジ日時 2025-04-19 20:01:56
合計ジャッジ時間 7,297 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

using std::cin;
using std::cout;

#define rep(i,n) for(int i = 0; i < (int)n; i++)
#define FOR(n) for(int i = 0; i < (int)n; i++)
#define repi(i,a,b) for(int i = (int)a; i < (int)b; i++)
#define all(x) x.begin(),x.end()
//#define mp make_pair
#define vi vector<int>
#define vvi vector<vi>
#define vvvi vector<vvi>
#define vvvvi vector<vvvi>
#define pii pair<int,int>
#define vpii vector<pair<int,int>>

template<typename T>
bool chmax(T &a, const T b) {if(a<b) {a=b; return true;} else {return false;}}
template<typename T>
bool chmin(T &a, const T b) {if(a>b) {a=b; return true;} else {return false;}}

using ll = long long;
using ld = long double;
using ull = unsigned long long;

const ll INF = numeric_limits<long long>::max() / 2;
const ld pi = 3.1415926535897932384626433832795028;
const ll mod = 998244353;
int dx[] = {1, 0, -1, 0, -1, -1, 1, 1};
int dy[] = {0, 1, 0, -1, -1, 1, -1, 1};

#define int long long

vector<int> farthest(vector<vector<pair<int, long long>>> g) {
    int n = (int)g.size();
    vector<long long> dp(n, 0);
    auto dfs = [&](int v, int p, auto self) -> void {
        for (auto e : g[v]) if (e.first != p) {
            self(e.first, v, self);
            dp[v] = max(dp[v], dp[e.first] + e.second);
        }
    };
    dfs(0, -1, dfs);
    vector<long long> ans = dp;
    auto dfs2 = [&](int v, int p, long long upper, long long weight, auto self) -> void {
        ans[v] = max(ans[v], upper + weight);
        vector<long long> dp_data;
        for (auto e : g[v]) if (e.first != p) {
            dp_data.emplace_back(dp[e.first] + e.second);
        }
        int child_sz = (int)dp_data.size();
        vector<long long> cuml(child_sz + 1, 0), cumr(child_sz + 1, 0);
        cuml[0] = upper + weight;
        for (int i = 0; i < child_sz; i++) cuml[i+1] = max(cuml[i], dp_data[i]);
        for (int i = child_sz-1; i >= 0; i--) cumr[i] = max(cumr[i+1], dp_data[i]);

        int id = 0;
        for (auto e : g[v]) if (e.first != p) {
            self(e.first, v, max(cuml[id], cumr[id+1]), e.second, self);
            id++;
        }
    };
    dfs2(0, -1, -1, 0, dfs2);
    return ans;
}



void solve() {
    int n;
    cin >> n;
    vector<vpii> g(n);
    FOR(n-1) {
        int u, v, w;
        cin >> u >> v >> w;
        --u;
        --v;
        g[u].emplace_back(v, w);
        g[v].emplace_back(u, w);
    }
    vi mx = farthest(g);
    cout << *max_element(all(mx)) << endl;
}

signed main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    solve();
    return 0;
}
0