RT,照着题解的思路写的
#include<iostream>
#include<cstring>
#define int long long
using namespace std;
const int N=2005;
int f[N][N],n,k,cnt;
int sz[N],head[N];
struct edge
{
int to,nxt,v;
}e[N*2];
void add(int u,int v,int w)
{
e[++cnt]=(edge){v,head[u],w};
head[u]=cnt;
}
void dfs(int now,int fa)
{
sz[now]=1;f[now][0]=f[now][1]=0;
for(int x=head[now];x;x=e[x].nxt)
{
if(e[x].to!=fa)
{
dfs(e[x].to,now);
sz[now]+=sz[e[x].to];
for(int i=min(k,sz[now]);i>=0;i--)
{
for(int j=0;j<=min(i,sz[e[x].to]);j++)
{
if(f[now][i-j]==-1) continue;
int w=j*(k-j)*e[x].v+(sz[e[x].to]-j)*(n-k-sz[e[x].to]+j)*e[x].v;
f[now][i]=max(f[now][i],f[now][i-j]+f[e[x].to][j]+w);
}
}
}
}
}
signed main()
{
cin>>n>>k;
memset(f,-1,sizeof f);
for(int i=1;i<n;i++)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
add(b,a,c);
}
dfs(1,0);
cout<<f[1][k];
return 0;
}