考场上打出来个(2^n n^2 log (n)),还文件错误RE了。。。
其实这不就是个变了一点点的树形背包,状态是节点(u)子树的(贡献)。
//#include <iostream>
#include <cstdio>
#include <cstring>
//#include <algorithm>
//#include <cmath>
#define R(a,b,c) for(register int a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long
#define ON_DEBUG
#ifdef ON_DEBUG
#define D_e_Line printf("
----------
")
#define D_e(x) cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);
#else
#define D_e_Line ;
#define D_e(x) ;
#define Pause() ;
#define FileOpen() ;
#endif
struct ios{
template<typename ATP>ios& operator >> (ATP &x){
x = 0; int f = 1; char c;
for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-') f = -1;
while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
x*= f;
return *this;
}
}io;
using namespace std;
const int N = 2007;
#define int long long
struct Edge{
int nxt, pre, w;
}e[N << 1];
int head[N], cntEdge;
inline void add(int u, int v, int w){
e[++cntEdge] = (Edge){ head[u], v, w}, head[u] = cntEdge;
}
int n, K;
int f[N][N], siz[N];
inline void DFS(int u, int fa){
siz[u] = 1;
f[u][0] = f[u][1] = 0;
for(register int i = head[u]; i; i = e[i].nxt){
int v = e[i].pre;
if(v == fa) continue;
DFS(v, u);
siz[u] += siz[v];
nR(j,Min(siz[u], K),0){
if(f[u][j] != -1)
f[u][j] += f[v][0] + siz[v] * (n - K - siz[v]) * e[i].w;
nR(t,Min(siz[v], j),1){
if(f[u][j - t] == -1) continue;
int val = (t * (K - t) + (siz[v] - t) * (n - K - siz[v] + t)) * e[i].w;
f[u][j] = Max(f[u][j], f[u][j - t] + f[v][t] + val);
}
}
}
}
#undef int
int main(){
#define int long long
//FileOpen();
io >> n >> K;
R(i,2,n){
int u, v, w;
io >> u >> v >> w;
add(u, v, w);
add(v, u, w);
}
Fill(f, -1);
if(n - K < K) K = n - K;
DFS(1, 0);
printf("%lld", f[1][K]);
return 0;
}