이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
namespace {
template <typename Fun>
struct YCombinator {
template <typename T>
YCombinator(T &&_fun) : fun(forward<T>(_fun)) {}
template <typename... Args>
decltype(auto) operator()(Args &&...args) {
return fun(ref(*this), forward<Args>(args)...);
}
private:
Fun fun;
};
template <typename T>
YCombinator(T &&) -> YCombinator<decay_t<T>>;
} // namespace
void solve() {
int n;
cin >> n;
vector<vector<pair<int, long>>> adj(n);
long low = -1;
for (int i = 0; i < n - 1; i++) {
int u, v;
long x;
cin >> u >> v >> x;
--u;
--v;
adj[u].emplace_back(v, x);
adj[v].emplace_back(u, x);
low -= x;
}
// root at a leaf
int root = -1;
for (int u = 0; u < n; u++) {
if ((int)adj[u].size() == 1) {
root = u;
break;
}
}
// dp[u][0] = max val such that it is root and no splitting
// dp[u][1] = max val such that it is root and has splitting
// dp[u][2] = max val such that it is connected to parent and no splitting
// dp[u][3] = max val such that it is connected to parent and has splitting
vector<array<long, 4>> dp(n);
YCombinator([&](auto self, int u, int p) -> void {
vector<pair<int, long>> ch;
for (auto [v, x] : adj[u]) {
if (v != p) {
ch.emplace_back(v, x);
self(v, u);
}
}
int k = (int)ch.size();
vector<long> com(k);
for (int i = 0; i < k; i++) {
auto [v, x] = ch[i];
com[i] = max(dp[v][0], x + dp[v][2]);
}
vector<long> pref(k + 1), suff(k + 1);
for (int i = 0; i < k; i++) {
pref[i + 1] = pref[i] + com[i];
}
for (int i = k - 1; i >= 0; i--) {
suff[i] = suff[i + 1] + com[i];
}
dp[u][0] = pref[k];
dp[u][1] = low;
if (k >= 2) {
array<long, 2> can;
can.fill(2 * low);
for (int i = 0; i < k; i++) {
auto [v, x] = ch[i];
can[1] = max(can[1] + com[i], can[0] + (x + dp[v][0]));
can[0] = max(can[0] + com[i], pref[i] + (x + dp[v][0]));
}
dp[u][1] = max(dp[u][1], can[1]);
}
for (int i = 0; i < k; i++) {
auto [v, x] = ch[i];
dp[u][1] = max(dp[u][1], pref[i] + max(dp[v][1], x + dp[v][3]) + suff[i + 1]);
}
dp[u][2] = low;
for (int i = 0; i < k; i++) {
auto [v, x] = ch[i];
dp[u][2] = max(dp[u][2], pref[i] + (x + dp[v][0]) + suff[i + 1]);
}
dp[u][3] = low;
for (int i = 0; i < k; i++) {
auto [v, x] = ch[i];
dp[u][3] = max(dp[u][3], pref[i] + (x + dp[v][1]) + suff[i + 1]);
}
})(root, -1);
long ans = max(dp[root][0], dp[root][1]);
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
solve();
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... |