有一棵点数为N的树,树边有边权。给你一个在0~N之内的正整数K,你要在这棵树中选择K个点,将其染成黑色,并
将其他的N-K个点染成白色。将所有点染色后,你会获得黑点两两之间的距离加上白点两两之间距离的和的收益。
问收益最大值是多少。
输入保证所有点之间是联通的。
N<=2000,0<=K<=N
来自 https://www.lydsy.com/JudgeOnline/problem.php?id=4033
卧槽原来我做过这样的题目?!!
直接做不好搞,可以考虑按边统计贡献。设f[I,j]表示以i为根的子树中分配j个黑点所有边的贡献和,枚举一个儿子k再枚举分配的黑点,一条边的贡献yy一下不就出来了
非常naive的代码风格,大概是去年八月份写的
#include
#include
#include
#include
#include
#include
#define rep(i, st, ed) for (int i = st; i <= ed; i += 1)
#define drp(i, st, ed) for (int i = st; i >= ed; i -= 1)
#define erg(i, st) for (int i = ls[st]; i; i = e[i].next)
#define fill(x, t) memset(x, t, sizeof(x))
#define max(x, y) (x)>(y)?(x):(y)
#define min(x, y) (x)<(y)?(x):(y)
#define ll long long
#define db double
#define INF 0x3f3f3f3f
#define N 2001
#define E 5001
#define L 2001
struct edge{int x, y, w, next;}e[E];
ll f[N][L], size[N], fa[N], ls[N];
int edgeCnt = 0, ans = 0;
inline ll read(){
ll x = 0; char ch = getchar();
while (ch < '0' || ch > '9'){ch=getchar();}
while (ch <= '9' && ch >= '0'){x = x * 10 + ch - '0'; ch = getchar();}
return x;
}
inline void addEdge(int x, int y, int w){
e[++ edgeCnt] = (edge){x, y, w, ls[x]}; ls[x] = edgeCnt;
e[++ edgeCnt] = (edge){y, x, w, ls[y]}; ls[y] = edgeCnt;
}
inline void dfs1(int now, int m){
rep(i, 1, m){f[now][i]=-1;}
size[now] = 1;
erg(i, now){
if (e[i].y != fa[now]){
fa[e[i].y] = now;
dfs1(e[i].y, m);
size[now] += size[e[i].y];
}
}
}
inline void dfs2(int now, int m){
erg(i, now){
if (e[i].y != fa[now]){
dfs2(e[i].y, m);
}
}
f[now][0]=f[now][1]=0;
erg(k, now){
int y = e[k].y;
if (fa[y] == now){
int lzh = min(m, size[now]);
drp(i, lzh, 0){
int lim = min(i,size[y]);
rep(j, 0, lim){
if (f[now][i-j] != -1 && f[y][j] != -1){
f[now][i]=max(f[now][i],f[now][i-j]+f[y][j]+e[k].w*(j*(m-j)+(size[y]-j)*(size[1]-size[y]-m+j)));
}
}
}
}
}
}
int main(void){
/* freopen("color.in","r",stdin);
freopen("color.out","w",stdout);
*/ int n = read();
int m = read();
rep(i, 2, n){
int x = read();
int y = read();
int w = read();
addEdge(x, y ,w);
}
fill(f, -1);
dfs1(1, m);
dfs2(1, m);
printf("%lld\n", f[1][m]);
return 0;
}