1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <bits/stdc++.h>
using namespace std;
using LL = long long;
#define FOR(i, l, r) for(int i = (l); i <= (r); ++i)
#define REP(i, n) FOR(i, 0, (n) - 1)
#define ssize(x) int(x.size())
template<class A, class B> auto& operator<<(ostream &o, pair<A, B> p) {
    return o << '(' << p.first << ", " << p.second << ')';
}
template<class T> auto operator<<(ostream &o, T x) -> decltype(x.end(), o) {
    o << '{'; int i = 0; for(auto e : x) o << (", ")+2*!i++ << e; return o << '}';
}
#ifdef DEBUG
#define debug(x...) cerr << "[" #x "]: ", [](auto... $) {((cerr << $ << "; "), ...); }(x), cerr << '\n'
#else
#define debug(...) {}
#endif

mt19937 rng(chrono::system_clock::now().time_since_epoch().count());

constexpr int MAX_DIF = 800;
constexpr LL inf = 1e18;

vector<vector<pair<int, int>>> adj;
vector<array<LL, 4>> dp;
vector<array<LL, 2>> pre(MAX_DIF * 2 + 1);
vector<array<LL, 2>> pos(MAX_DIF * 2 + 1);

void dfs(int v, int p) {
    for(auto [u, w] : adj[v]) 
        if(u != p) 
            dfs(u, v);

    REP(i, MAX_DIF * 2 + 1) pre[i] = {-inf, -inf};
    pre[MAX_DIF][0] = 0;

    for(auto [u, w] : adj[v]) if(u != p) {
        auto prev3 = dp[u][3];
        for(int i = 2; i >= 0; i--)
            dp[u][i + 1] = dp[u][i] + w;
        dp[u][0] = max(dp[u][0], prev3 + w);

        REP(i, MAX_DIF * 2 + 1) pos[i] = {-inf, -inf};
        REP(dif, MAX_DIF * 2 + 1) {
            REP(k, 4) REP(r, 2) {
                int last_dif = dif - (k == 1) + (k == 3);
                int last_r = r ^ (k == 2);
                if(0 <= last_dif && last_dif <= MAX_DIF * 2) 
                    pos[dif][r] = max(pos[dif][r], pre[last_dif][last_r] + dp[u][k]);
            }
        }
        swap(pre, pos);
    }

    dp[v][0] = pre[MAX_DIF][0];
    dp[v][1] = pre[MAX_DIF + 1][0];
    dp[v][2] = pre[MAX_DIF][1];
    dp[v][3] = pre[MAX_DIF - 1][0];
}

int main() {
    cin.tie(0)->sync_with_stdio(0);

    int n;
    cin >> n;

    adj.resize(n);
    REP(i, n - 1) {
        int u, v, w;
        cin >> u >> v >> w;
        adj[u - 1].emplace_back(v - 1, w);
        adj[v - 1].emplace_back(u - 1, w);
    }

    REP(i, n) {
        auto &a = adj[i];
        shuffle(a.begin(), a.end(), rng);
    }

    dp.resize(n);
    dfs(0, -1);

    cout << dp[0][0] << "\n";
}