/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 5ms 4.961 MiB
#2 Accepted 76ms 5.066 MiB
#3 Accepted 49ms 5.172 MiB
#4 Accepted 12ms 5.547 MiB
#5 Accepted 45ms 5.066 MiB
#6 Accepted 280ms 6.184 MiB
#7 Accepted 252ms 6.277 MiB
#8 Accepted 272ms 6.27 MiB
#9 Accepted 232ms 8.32 MiB
#10 Accepted 154ms 26.52 MiB
#11 Accepted 159ms 26.52 MiB
#12 Accepted 249ms 26.52 MiB
#13 Accepted 160ms 13.816 MiB
#14 Accepted 360ms 35.211 MiB
#15 Accepted 359ms 29.039 MiB
#16 Accepted 271ms 6.121 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:27
Judged At
2025-07-14 22:09:27
Judged By
Score
100
Total Time
360ms
Peak Memory
35.211 MiB