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 lsb(x) (x & (-x))
#define ll long long
#define ull unsigned long long
// 217
// 44
/*const int MOD = ;
inline int lgput(int a, int b) {
int ans = 1;
while(b > 0) {
if(b & 1) ans = (1LL * ans * a) % MOD;
b >>= 1;
a = (1LL * a * a) % MOD;
}
return ans;
}
inline void mod(int &x) {
if(x >= MOD)
x -= MOD;
}
inline void add(int &x, int y) {
x += y;
mod(x);
}
inline void sub(int &x, int y) {
x += MOD - y;
mod(x);
}
inline void mul(int &x, int y) {
x = (1LL * x * y) % MOD;
}*/
using namespace std;
const ll INF = 1e10;
const int MAXN = (int) 2e5;
vector < pair <int, int> > g[MAXN + 1];
ll dp[MAXN + 1][2], cst[MAXN + 1];
// dp[nod][0] = nu ai spart nimic
// dp[nod][1] = ai spart un fiu de tata
void dfs(int nod, int par) {
vector <ll> cur(2, -INF);
cur[0] = 0;
for(auto it : g[nod]) {
if(it.first != par) {
cst[it.first] = it.second;
dfs(it.first, nod);
ll mx = max(dp[it.first][1] + it.second, dp[it.first][0]);
cur[1] = max(cur[0] + dp[it.first][0] + it.second, cur[1] + mx);
cur[0] += mx;
}
}
dp[nod][0] = cur[0], dp[nod][1] = cur[1];
}
ll ans;
void solve(int nod, int par) {
ans = max(ans, dp[nod][0]);
vector < pair <ll, int> > vals;
for(auto it : g[nod]) {
vals.push_back({dp[it.first][0] + it.second - max(dp[it.first][0], dp[it.first][1] + it.second), it.first});
}
sort(vals.begin(), vals.end(), greater < pair <ll, int> >());
for(auto it : g[nod]) {
if(it.first != par) {
ll a = dp[nod][0], b = dp[nod][1], c = dp[it.first][0], d = dp[it.first][1];
ll mx = max(dp[it.first][0], dp[it.first][1] + it.second);
dp[nod][0] -= mx;
if(it.first != vals[0].second) {
dp[nod][1] -= mx;
}
else {
if(vals.size() > 1) {
dp[nod][1] -= dp[it.first][0] + it.second;
dp[nod][1] += vals[1].first;
}
else {
dp[nod][1] = -INF;
}
}
mx = max(dp[nod][0], dp[nod][1] + it.second);
dp[it.first][1] = max(dp[it.first][1] + mx, dp[it.first][0] + dp[nod][0] + it.second);
dp[it.first][0] += mx;
solve(it.first, nod);
dp[nod][0] = a, dp[nod][1] = b, dp[it.first][0] = c, dp[it.first][1] = d;
}
}
}
int main() {
//ifstream cin("A.in");
//ofstream cout("A.out");
int i, n;
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n;
for(i = 1; i < n; i++) {
int x, y, z;
cin >> x >> y >> z;
g[x].push_back({y, z});
g[y].push_back({x, z});
}
dfs(1, 0);
solve(1, 0);
cout << ans;
//cin.close();
//cout.close();
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... |