/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 5ms 5.02 MiB
#2 Accepted 53ms 5.113 MiB
#3 Accepted 50ms 5.16 MiB
#4 Accepted 12ms 5.441 MiB
#5 Accepted 45ms 5.02 MiB
#6 Accepted 285ms 6.293 MiB
#7 Accepted 242ms 6.219 MiB
#8 Accepted 243ms 6.273 MiB
#9 Accepted 232ms 8.266 MiB
#10 Accepted 150ms 26.512 MiB
#11 Accepted 165ms 26.469 MiB
#12 Accepted 248ms 26.516 MiB
#13 Accepted 162ms 13.906 MiB
#14 Accepted 364ms 35.301 MiB
#15 Accepted 360ms 29.156 MiB
#16 Accepted 275ms 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() {


    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:09:06
Judged At
2025-07-14 22:09:06
Judged By
Score
100
Total Time
364ms
Peak Memory
35.301 MiB