# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
883280 | nguyentunglam | Beads and wires (APIO14_beads) | C++17 | 115 ms | 26096 KiB |
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 all(v) v.begin(), v.end()
#define endl "\n"
using namespace std;
const int N = 2e5 + 10;
int f[N], g[N], h[N];
int _f[N], _g[N], _h[N];
int maxw[2][N];
vector<pair<int, int> > adj[N];
void dfs(int u, int p) {
maxw[0][u] = maxw[1][u] = -1e9;
for(auto &[v, w] : adj[u]) if (v != p) {
dfs(v, u);
h[v] = max(f[v], g[v] + w);
f[u] += h[v];
maxw[1][u] = max(maxw[1][u], w + f[v] - h[v]);
if (maxw[0][u] < maxw[1][u]) swap(maxw[0][u], maxw[1][u]);
}
g[u] = f[u] + maxw[0][u];
}
void _dfs(int u, int p, int w, int pre_cost) {
if (p) {
_f[u] = f[p] - h[u] + _h[p];
int cost = maxw[0][p];
if (w + f[u] - h[u] == cost) cost = maxw[1][p];
cost = max(cost, pre_cost);
_g[u] = _f[u] + cost;
_h[u] = max(_f[u], _g[u] + w);
int new_cost = w + _f[u] - _h[u];
pre_cost = new_cost;
}
for(auto &[v, next_w] : adj[u]) if (v != p) {
_dfs(v, u, next_w, pre_cost);
}
}
int32_t main() {
#define task ""
cin.tie(0) -> sync_with_stdio(0);
if (fopen("task.inp", "r")) {
freopen("task.inp", "r", stdin);
freopen("task.out", "w", stdout);
}
if (fopen(task".inp", "r")) {
freopen (task".inp", "r", stdin);
freopen (task".out", "w", stdout);
}
int n; cin >> n;
for(int i = 1; i < n; i++) {
int a, b, c; cin >> a >> b >> c;
adj[a].emplace_back(b, c);
adj[b].emplace_back(a, c);
}
dfs(1, 0);
_dfs(1, 0, 0, -1e9);
int ans = 0;
for(int i = 1; i <= n; i++) {
ans = max(ans, f[i] + _h[i]);
}
cout << ans;
}
Compilation message (stderr)
# | 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... |