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>
#define ll int
#define pll pair<ll, ll>
#define pb push_back
#define fi first
#define se second
using namespace std;
const int N = 3e5 + 5;
const ll mod = 1e9 + 7;
ll n, m, a[N], b[N], dp[N], gp[N], tong;
vector<pll> adj[N];
void dfs(ll u, ll p, ll s)
{
ll sum = 0;
ll mx1 = -mod, mx2 = -mod;
for (pll v : adj[u])
{
if (v.se == p)
continue;
dfs(v.se, u, v.fi);
sum += max(dp[v.se], gp[v.se]);
int val = dp[v.se] - max(dp[v.se], gp[v.se]) + v.fi;
if (mx1 < val)
{
mx2 = mx1;
mx1 = val;
}
else if (mx2 < val)
mx2 = val;
}
dp[u] = sum;
a[u] = sum;
for (pll v : adj[u])
{
if (v.se == p)
continue;
int val = dp[u] - max(dp[v.se], gp[v.se]);
gp[u] = max(gp[u], dp[v.se] + val + v.fi + s);
int mx = v.fi + dp[v.se] - max(dp[v.se], gp[v.se]);
if (mx == mx1)
mx = mx2;
else
mx = mx1;
a[u] = max(a[u], a[v.se] + val + v.fi + mx);
a[u] = max(a[u], a[v.se] + val);
for (pll z : adj[v.se])
{
if (z.se == u)
continue;
int valz = dp[v.se] - max(dp[z.se], gp[z.se]);
a[u] = max(a[u], val + valz + v.fi + z.fi + a[z.se]);
}
}
}
void sol()
{
cin >> n;
for (int i = 1; i < n; i++)
{
ll x, y, w;
cin >> x >> y >> w;
adj[x].pb({w, y});
adj[y].pb({w, x});
}
dfs(1, 0, 0);
cout << a[1];
}
int main()
{
cin.tie(0);
cout.tie(0);
ios_base::sync_with_stdio(0);
int test = 1;
//cin >> test;
while (test-- > 0)
sol();
return 0;
}
/*
10
4 10 2
1 2 21
1 3 13
6 7 1
7 9 5
2 4 3
2 5 8
1 6 55
6 8 34
*/
// ctrl + F8 = compile
// ctrl + F9 = run
# | 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... |