## Codeforces 294E Shaass the Great 树形dp

Shaass the Great

```#include<bits/stdc++.h>
#define LL long long
#define LD long double
#define ull unsigned long long
#define fi first
#define se second
#define mk make_pair
#define PLL pair<LL, LL>
#define PLI pair<LL, int>
#define PII pair<int, int>
#define SZ(x) ((int)x.size())
#define ALL(x) (x).begin(), (x).end()
#define fio ios::sync_with_stdio(false); cin.tie(0);

using namespace std;

const int N = 5000 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-8;
const double PI = acos(-1);

template<class T, class S> inline void add(T &a, S b) {a += b; if(a >= mod) a -= mod;}
template<class T, class S> inline void sub(T &a, S b) {a -= b; if(a < 0) a += mod;}
template<class T, class S> inline bool chkmax(T &a, S b) {return a < b ? a = b, true : false;}
template<class T, class S> inline bool chkmin(T &a, S b) {return a > b ? a = b, true : false;}

int n;
int in[N], ot[N], who[N], idx;
int fa[N], fsz[N], sz[N], wfa[N];
LL dp[N][2];
bool is[N];

vector<PII> G[N];
LL ret, ans;

void dfs(int u) {
in[u] = ++idx;
who[idx] = u;
sz[u] = 1;
for(auto &e : G[u]) {
if(e.se == fa[u]) continue;
fa[e.se] = u;
wfa[e.se] = e.fi;
dfs(e.se);
sz[u] += sz[e.se];
}
fsz[u] = n - sz[u];
ret += 1LL * sz[u] * fsz[u] * wfa[u];
ot[u] = idx;
}

void dfs2(int u, LL tmp, LL &ret, int csz) {
chkmin(ret, tmp);
for(auto &e : G[u]) {
if(e.se == fa[u]) continue;
LL ntmp = tmp;
ntmp -= 1LL * e.fi * sz[e.se] * fsz[e.se];
ntmp += 1LL * e.fi * (sz[e.se] + csz) * (fsz[e.se] - csz);
dfs2(e.se, ntmp, ret, csz);
}
}

void dfs3(int u, int ban, int csz) {
dp[u][0] = dp[u][1] = is[u] = 0;
if(in[u] <= in[ban] && ot[ban] <= ot[u]) is[u] = true;
LL mx = 0;
for(auto &e : G[u]) {
if(e.se == fa[u] || e.se == ban) continue;
dfs3(e.se, ban, csz);
chkmin(dp[u][0], dp[e.se][0]);
if(is[u]) {
if(is[e.se]) {
dp[u][1] = dp[e.se][1];
} else {
chkmin(mx, dp[e.se][1]);
}
} else {
chkmin(dp[u][1], dp[e.se][1]);
}
}
if(is[u]) {
chkmin(dp[u][0], dp[u][1] + mx);
dp[u][1] -= 1LL * wfa[u] * sz[u] * fsz[u];
dp[u][1] += 1LL * wfa[u] * (sz[u] - csz) * (fsz[u] + csz);
} else {
dp[u][1] -= 1LL * wfa[u] * sz[u] * fsz[u];
dp[u][1] += 1LL * wfa[u] * (sz[u] + csz) * (fsz[u] - csz);
chkmin(dp[u][1], 0);
}
}

LL solve(int x) {
LL ret = 0;
dfs2(x, 0, ret, fsz[x]);
dfs3(1, x, sz[x]);
ret += dp[1][0];
return ret;
}

int main() {
scanf("%d", &n);
for(int i = 1; i < n; i++) {
int a, b, w;
scanf("%d%d%d", &a, &b, &w);
G[a].push_back(mk(w, b));
G[b].push_back(mk(w, a));
}
dfs(1);
ans = ret;
for(int i = 2; i <= n; i++) {
chkmin(ans, ret + solve(i));
}
printf("%lld\n", ans);
return 0;
}

/*
*/```