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 <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
typedef long long ll;
const int N = 200010;
const int INF = 2e9;
int n;
vector<pair<int, int>> g[N];
int dp[N][2];
int up[N][2];
int ans = 0;
void dfs(int v, int p = -1, int pc = 0) {
int mx = -INF, sum = 0;
for (auto [u, c] : g[v]) {
if (u != p) {
dfs(u, v, c);
sum += dp[u][1];
mx = max(mx, dp[u][0] - dp[u][1] + c);
}
}
dp[v][0] = sum;
dp[v][1] = sum + max(0, mx + pc);
}
void go(int v, int p = -1, int pc = 0) {
int sum = 0;
multiset<int> st;
if (p != -1) {
sum += up[v][1];
st.insert(up[v][0] - up[v][1] + pc);
}
for (auto [u, c] : g[v]) {
if (u != p) {
sum += dp[u][1];
st.insert(dp[u][0] - dp[u][1] + c);
}
}
ans = max(ans, sum);
for (auto [u, c] : g[v]) {
if (u != p) {
sum -= dp[u][1];
st.erase(st.find(dp[u][0] - dp[u][1] + c));
up[u][0] = sum;
up[u][1] = sum + (st.empty() ? 0 : max(0, *st.rbegin() + c));
go(u, v, c);
sum += dp[u][1];
st.insert(dp[u][0] - dp[u][1] + c);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 0; i < n - 1; ++i) {
int a, b, c;
cin >> a >> b >> c;
g[a].push_back({b, c});
g[b].push_back({a, c});
}
dfs(1);
go(1);
cout << ans << endl;
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... |