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;
const int INF = 2e9 + 10;
int main()
{
cin.tie(0)->sync_with_stdio(0);
int n;
cin >> n;
vector<vector<pair<int, int>>> g(n);
for (int i = 0; i < n - 1; i++)
{
int u, v, w;
cin >> u >> v >> w;
u--, v--;
g[u].emplace_back(v, w);
g[v].emplace_back(u, w);
}
vector<bool> vis(n);
vector<vector<int>> dp(n, vector<int>(4, -INF));
function<void(int, int)> dfs = [&](int u, int W)
{
vis[u] = true;
dp[u][0] = dp[u][2] = 0;
vector<int> res;
for (auto &[v, w] : g[u])
{
if (!vis[v])
{
dfs(v, w);
dp[u][0] += max(dp[v][0], dp[v][1]);
res.push_back(dp[v][0] + w - max(dp[v][0], dp[v][1]));
}
}
sort(begin(res), end(res), greater<>());
if (res.size() >= 1)
{
dp[u][1] = dp[u][0] + W + res[0];
for (auto &[v, w] : g[u])
{
if (!vis[v])
{
dp[u][2] = max(dp[u][2], max(dp[v][2], dp[v][3]) - max(dp[v][0], dp[v][1]) + dp[u][0]);
dp[u][3] = max(dp[u][3], dp[v][2] + w + W - max(dp[v][0], dp[v][1]) + dp[u][0]);
}
}
}
if (res.size() >= 2)
{
for (auto &[v, w] : g[u])
{
if (!vis[v])
{
int x = dp[v][0] + w - max(dp[v][0], dp[v][1]) == res[0] ? res[1] : res[0];
dp[u][2] = max(dp[u][2], dp[u][0] + dp[v][2] + w - max(dp[v][0], dp[v][1]) + x);
}
}
}
dp[u][2] = max(dp[u][2], dp[u][0]);
dp[u][3] = max(dp[u][3], dp[u][1]);
vis[u] = false;
};
dfs(0, -INF);
int ans = max(dp[0][2], dp[0][3]);
cout << ans << '\n';
return 0;
}
# | 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... |