/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 5ms 5.066 MiB
#2 Accepted 23ms 5.184 MiB
#3 Accepted 21ms 5.191 MiB
#4 Accepted 8ms 5.52 MiB
#5 Accepted 23ms 5.02 MiB
#6 Accepted 97ms 6.383 MiB
#7 Accepted 86ms 6.18 MiB
#8 Accepted 89ms 6.27 MiB
#9 Accepted 88ms 8.312 MiB
#10 Accepted 68ms 26.52 MiB
#11 Accepted 69ms 26.516 MiB
#12 Accepted 94ms 26.359 MiB
#13 Accepted 62ms 13.809 MiB
#14 Accepted 156ms 35.148 MiB
#15 Accepted 150ms 29.07 MiB
#16 Accepted 86ms 6.02 MiB

Code

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

const int MAXN = 200005;
const long long MINF = -1e18;

vector<pair<int, int>> g[MAXN];
long long W[MAXN];
long long dp1[MAXN], dp2[MAXN], dp3[MAXN];
long long inc[MAXN], exc[MAXN];
long long res;

void dfs(int v, int p) {
    vector<long long> child_inc;

    for (auto [to, cost] : g[v]) {
        if (to == p) continue;

        dp1[to] = dp1[v] + W[to];
        dp2[to] = dp2[v] + cost;
        dp3[to] = dp1[to] - 2 * dp2[to];

        dfs(to, v);

        child_inc.push_back(inc[to]);
    }

    if (child_inc.size() >= 2) {
        sort(child_inc.rbegin(), child_inc.rend());
        long long local_pair = child_inc[0] + child_inc[1] - 2 * dp3[v];
        res = max(res, local_pair + W[v]);
    }

    for (auto [to, _] : g[v]) {
        if (to == p) continue;
        res = max(res, exc[to] - dp3[v] + W[v]);
    }

    if (!child_inc.empty()) {
        exc[v] = *max_element(child_inc.begin(), child_inc.end());
    } else {
        exc[v] = MINF;
    }

    inc[v] = max(dp3[v], exc[v]);
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int T; cin >> T;
    while (T--) {
        int N; cin >> N;

        for (int i = 1; i <= N; ++i) {
            cin >> W[i];
            g[i].clear();
            inc[i] = exc[i] = MINF;  
        }

        for (int i = 1; i < N; ++i) {
            int u, v, c;
            cin >> u >> v >> c;
            g[u].emplace_back(v, c);
            g[v].emplace_back(u, c);
        }

        dp1[1] = W[1];
        dp2[1] = 0;
        dp3[1] = dp1[1] - 2 * dp2[1];
        res = MINF;

        dfs(1, -1);

        cout << res << '\n';  
    }

    return 0;
}

Information

Submit By
Type
Submission
Problem
P1205 E. Make Cycle in Tree
Language
C++17 (G++ 13.2.0)
Submit At
2025-07-14 22:07:50
Judged At
2025-07-14 22:07:50
Judged By
Score
100
Total Time
156ms
Peak Memory
35.148 MiB