제출 #1021361

#제출 시각아이디문제언어결과실행 시간메모리
1021361PVSekhar구슬과 끈 (APIO14_beads)C++17
100 / 100
85 ms21448 KiB
#include <bits/stdc++.h>
using namespace std; 
#define ll long long
const int MOD = 1e9 + 7;
const int N = 2e5 + 2;

int ans = 0, o[N], t[N];
vector<vector<pair<int,int>>> edges(N);

void dfs1(int node, int parent) {
    int val = 0;
    for (auto child : edges[node]) {
        if (child.first == parent) continue;
        dfs1(child.first, node);
        if (t[child.first] != -1) t[child.first] += child.second;
        t[child.first] = max(t[child.first], o[child.first]);
        o[child.first] += child.second;
        val += t[child.first];
    }
    o[node] = val;
    for (auto child : edges[node]) {
        if (child.first == parent) continue;
        t[node] = max(t[node], val - t[child.first] + o[child.first]);
    }
}

void dfs2(int node, int parent, int o_val, int t_val) {
    int val = 0, val1 = INT_MIN, val2 = INT_MIN;
    if (node != 1) val += t_val, val1 = o_val - t_val;
    for (auto child : edges[node]) {
        if (child.first == parent) continue;
        val += t[child.first];
        if (val1 == INT_MIN) val1 = o[child.first] - t[child.first];
        else {
            val2 = max(val2, o[child.first] - t[child.first]);
            if (val2 > val1) swap(val1, val2);
        }
    }
    ans = max(ans, val + max(0, val1 + val2));
    for (auto child : edges[node]) {
        if (child.first == parent) continue;
        val -= t[child.first];
        if (o[child.first] - t[child.first] == val1) dfs2(child.first, node, val + child.second, max(val, val + val2 + child.second));
        else dfs2(child.first, node, val + child.second, max(val, val + val1 + child.second));
        val += t[child.first];
    }
}

void solve() {
    int n, a, b, c;
    cin >> n;
    for (int i = 1; i < n; i++) {
        cin >> a >> b >> c;
        edges[a].push_back(make_pair(b, c));
        edges[b].push_back(make_pair(a, c));
    }
    for (int i = 1; i <= n; i++) o[i] = t[i] = -1;
    dfs1(1, 0);
    dfs2(1, 0, 0, 0);
    cout << ans << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    // #ifndef ONLINE_JUDGE
    // freopen("input.in", "r", stdin);
	// freopen("output.out", "w", stdout);
    // #endif
    ll t;
    t = 1;
    // cin >> t;
    while(t--) {
        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...