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>
#pragma GCC Optimize("O3")
#define FOR(i, x, y) for (ll i = x; i < y; i++)
#define x first
#define y second
typedef long long ll;
using namespace std;
vector<pair<ll, ll>> graph[200001];
ll dp[200001][4];
void dfs(ll node, ll parent, ll edge) {
ll best = INT_MIN, second = INT_MIN;
for (pair<ll, ll> i : graph[node]) {
if (i.x != parent) {
dfs(i.x, node, i.y);
dp[node][0] += max(max(dp[i.x][0], dp[i.x][1]), max(dp[i.x][2], dp[i.x][3]));
}
}
for (pair<ll, ll> i : graph[node]) {
if (i.x != parent) {
dp[node][2] = max(dp[node][2], dp[node][0] - max(max(dp[i.x][0], dp[i.x][1]), max(dp[i.x][2], dp[i.x][3])) + dp[i.x][0] + i.second + edge);
dp[node][3] = max(dp[node][3], dp[node][0] - max(max(dp[i.x][0], dp[i.x][1]), max(dp[i.x][2], dp[i.x][3])) + dp[i.x][1] + i.second + edge);
if (max(dp[i.x][0], dp[i.x][1]) + i.second - max(max(dp[i.x][0], dp[i.x][1]), max(dp[i.x][2], dp[i.x][3])) > best) {
second = best;
best = max(dp[i.x][0], dp[i.x][1]) + i.second - max(max(dp[i.x][0], dp[i.x][1]), max(dp[i.x][2], dp[i.x][3]));
} else if (max(dp[i.x][0], dp[i.x][1]) + i.second - max(max(dp[i.x][0], dp[i.x][1]), max(dp[i.x][2], dp[i.x][3])) > second) {
second = max(dp[i.x][0], dp[i.x][1]) + i.second - max(max(dp[i.x][0], dp[i.x][1]), max(dp[i.x][2], dp[i.x][3]));
}
}
}
dp[node][1] = dp[node][0] + best + second;
}
int main() {
iostream::sync_with_stdio(false);
cin.tie(0);
ll n;
cin >> n;
FOR(i, 1, n) {
ll a, b, c;
cin >> a >> b >> c;
graph[a].push_back({b, c});
graph[b].push_back({a, c});
}
dfs(1, 0, 0);
cout << max(dp[1][0], dp[1][1]) << '\n';
return 0;
}
Compilation message (stderr)
beads.cpp:2:0: warning: ignoring #pragma GCC Optimize [-Wunknown-pragmas]
#pragma GCC Optimize("O3")
# | 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... |