이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 200'005;
const ll inf = 1e18;
ll dp[N][2][2];
vector<array<ll, 2>> adj[N];
void build(int i, int p) {
vector<array<ll, 2>> newadj;
for (auto [nxt, w] : adj[i]) {
if (nxt == p) continue;
build(nxt, i);
newadj.push_back({nxt, w});
}
adj[i] = newadj;
}
ll dfs(int i, int st, int carry) {
if (~dp[i][st][carry]) {
return dp[i][st][carry];
}
ll ans = 0;
if (carry) {
ans = -inf;
}
if (!st) {
for (auto [nxt, w] : adj[i]) {
ans = max(ans, dfs(nxt, 0, 0));
}
}
ll s = 0;
for (auto [nxt, w] : adj[i]) {
s += max(dfs(nxt, 1, 1) + w, 0ll);
}
if (!carry) {
ans = max(ans, s);
} else {
for (auto [nxt, w] : adj[i]) {
ans = max(ans, s - max(dfs(nxt, 1, 1) + w, 0ll) + dfs(nxt, 1, 0) + w);
}
}
ll mx[2] = {-inf, -inf};
for (auto [nxt, w] : adj[i]) {
ll v = - max(dfs(nxt, 1, 1) + w, 0ll) + dfs(nxt, 1, 0) + w;
if (v > mx[1]) {
mx[1] = v;
}
if (mx[0] < mx[1]) swap(mx[0], mx[1]);
}
if (!carry) {
ans = max(ans, s + mx[0] + mx[1]);
}
return dp[i][st][carry] = ans;
}
int main() {
ios_base::sync_with_stdio(0), cin.tie(0);
memset(dp, -1, sizeof dp);
int n;
cin >> n;
for (int i = 1, u, v, w; i < n; i++) {
cin >> u >> v >> w;
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
build(1, 0);
cout << dfs(1, 0, 0) << '\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... |