This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
#define pb emplace_back
#define int long long
const int N = 2e5 + 1;
typedef pair<int,int> ii;
vector<ii> g[N];
int f[N][2];
int ans = 0;
void dfs(int u,int p) {
int mx = -1e9;
for(ii e : g[u]) {
int v = e.first;
int c = e.second;
if (v == p) continue;
dfs(v,u);
f[u][0] += max(f[v][1] + c,f[v][0]);
if (mx < min(c,f[v][0] - f[v][1]))
mx = min(c,f[v][0] - f[v][1]);
}
f[u][1] = f[u][0] + mx;
}
void cal(int u,int p,int lz) {
ans = max(ans,f[u][0]);
int Sum = f[u][0];
int mx1 = lz;
int mx2 = -1e9;
for(ii e : g[u]) {
int v = e.first;
int c = e.second;
if (v ^ p) {
if (mx2 < min(c,f[v][0] - f[v][1]))
mx2 = min(c,f[v][0] - f[v][1]);
if (mx1 < mx2)
swap(mx1,mx2);
}
}
for(ii e : g[u]) {
int v = e.first;
int c = e.second;
if (v ^ p) {
int prv = max(f[v][1] + c,f[v][0]);
int cur = min(c,f[v][0] - f[v][1]);
if (cur ^ mx1)
cur = mx2;
cur = mx1 + mx2 - cur;
Sum -= prv; //now Sum is equal to f[u][0] when we start dfs from node v
f[v][0] += max(cur + c,0ll) + Sum;
f[v][1] = max(cur + f[v][0],f[v][1]);
cal(v,u,min(c,-cur));
Sum += prv;
}
}
}
signed main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int n; cin >> n;
for(int i = 1 ; i < n ; ++i) {
int x; cin >> x;
int y; cin >> y;
int c; cin >> c;
g[x].pb(y,c);
g[y].pb(x,c);
}
dfs(1,0);
cal(1,0,-1e9);
cout << ans << endl;
}
/*
5
1 2 10
1 3 40
1 4 15
1 5 20
*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |