Submission #1340853

#TimeUsernameProblemLanguageResultExecution timeMemory
1340853fatelessBeads and wires (APIO14_beads)C++20
0 / 100
1 ms344 KiB
// #pragma GCC optimize("O3,Ofast,unroll-loops")
#include <bits/stdc++.h>
using namespace std;
 
#define now chrono::steady_clock::now().time_since_epoch().count()
#define speedup cin.tie(0)->sync_with_stdio(0);
#define bitcount __builtin_popcount
#define all(x) begin(x), end(x)
#define int long long
#define pb push_back
#define vc vector
using pii = array<int, 2>;

const int N = 1e4 + 1, inf = 1e18;
static int dp[N][3], pc[N];
inline void solve() {
    int n; cin >> n;
    vc<vc<pii>> adj (n + 1);
    for (int i = 1; i < n; i++) {
        int a, b, c; cin >> a >> b >> c;
        adj[a].pb({b, c}); adj[b].pb({a, c});
    }

    auto dfs = [&](auto &&dfs, int a, int p) -> void {
        int op1 = -inf, op2 = -inf;
        for (auto [b, c] : adj[a]) {
            if (b == p) continue; 
            else pc[b] = c; 
            dfs(dfs, b, a);

            // dp[a][0]
            int val0 =  max({dp[b][0], dp[b][1], dp[b][2]});
            int val1 = max(dp[b][0], dp[b][2]) + c - val0;
            dp[a][0] += val0;
            
            // dp[a][1 && 2]
            if (op1 < val1) tie(op2, op1) = {op1, val1};
            else op2 = max(op2, val1);
        }

        dp[a][2] = dp[a][0] + op1 + op2;
        dp[a][1] = dp[a][0] + op1 + pc[a];
    };

    int ans = -inf;
    for (int i = 1; i <= n; i++) {
        dfs(dfs, i, i);
        ans = max(ans, dp[i][0]);
        for (int j = 1; j <= n; j++) {
            pc[j] = 0;
            dp[j][0] = dp[j][1] = dp[j][2] = 0;
        }
    }

    cout << ans;
}

signed main() {
    speedup;
    solve();

    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...