이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
#define nl '\n'
#ifdef LOCAL
#include "template/debug.hpp"
#else
#define dbg(...) ;
#define timer(...) ;
#endif
const int mxN = 2e5 + 5;
int dp[mxN][2][2], up[mxN];
std::vector<std::pair<int, int>> adj[mxN];
int N;
int dfs(int u, int p, int e, int b) {
if (dp[u][e][b] != -1) return dp[u][e][b];
std::vector<int> child;
for (auto [v, c] : adj[u]) {
if (v == p) continue;
up[v] = c;
child.push_back(v);
dfs(v, u, 0, 0);
dfs(v, u, 0, 1);
dfs(v, u, 1, 0);
dfs(v, u, 1, 1);
}
int& ans = dp[u][e][b];
int sum_e_no_b = 0;
for (int v : child) {
sum_e_no_b += dp[v][1][0];
}
ans = sum_e_no_b;
if (b) {
for (int v : child) {
ans = std::max(ans, sum_e_no_b - dp[v][1][0] + dp[v][1][1]);
}
if (child.size() >= 2) {
std::sort(child.begin(), child.end(), [&](int i, int j) {
return dp[i][0][0] + up[i] - dp[i][1][0] >
dp[j][0][0] + up[j] - dp[j][1][0];
});
for (int v : child) {
int cand = sum_e_no_b - dp[v][1][0] + dp[v][0][1] + up[v];
int vv = child[0] == v ? child[1] : child[0];
cand += dp[vv][0][0] + up[vv] - dp[vv][1][0];
dbg(v + 1, vv + 1, cand, u + 1);
ans = std::max(ans, cand);
}
}
}
if (e) {
if (b) {
for (int v : child) {
int cand = sum_e_no_b + up[u] + up[v] + dp[v][0][1] - dp[v][1][0];
ans = std::max(ans, cand);
}
} else {
for (int v : child) {
int cand = sum_e_no_b + up[u] + up[v] + dp[v][0][0] - dp[v][1][0];
ans = std::max(ans, cand);
}
}
}
dbg(u + 1, e, b, ans, child);
return ans;
}
signed main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
memset(dp, -1, sizeof(dp));
std::cin >> N;
for (int i = 0; i + 1 < N; i++) {
int u, v, c;
std::cin >> u >> v >> c;
--u, --v;
adj[u].emplace_back(v, c);
adj[v].emplace_back(u, c);
}
std::cout << dfs(0, 0, 0, 1) << nl;
}
/*
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
*/
# | 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... |