题意:
在树中取k个点,这些点中任意点的距离和要最小。
题解:
dp[i][j],表示以i为跟的子树选择j个节点对应的距离对整体的贡献,就是一个树形背包。
dp[u][j] = min { dp[u][j-t] + dp[v][t] + cost(t * (k-t) * w * 2) } cost是连接u和v的边对整体的贡献。
#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#define B(x) (1<<(x))
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned ui;
const int oo = 0x3f3f3f3f;
//const ll OO = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-9;
#define lson rt<<1
#define rson rt<<1|1
void cmax(int& a, int b){ if (b > a)a = b; }
void cmin(int& a, int b){ if (b < a)a = b; }
void cmax(ll& a, ll b){ if (b > a)a = b; }
void cmin(ll& a, ll b){ if (b < a)a = b; }
void cmax(double& a, double b){ if (a - b < eps) a = b; }
void cmin(double& a, double b){ if (b - a < eps) a = b; }
void add(int& a, int b, int mod){ a = (a + b) % mod; }
void add(ll& a, ll b, ll mod){ a = (a + b) % mod; }
const ll MOD = 1000000007;
const int maxn = 2100;
struct EDGE{
int v, w, next;
}E[maxn << 1];
int head[maxn], tol;
ll dp[maxn][maxn];
int n, k;
void Init(){
memset(head, -1, sizeof head);
tol = 0;
}
void add_edge(int u, int v, int w){
E[tol].v = v;
E[tol].w = w;
E[tol].next = head[u];
head[u] = tol++;
}
void tree_dp(int u, int pre){
for (int i = 2; i <= k; i++)
dp[u][i] = oo;
dp[u][0] = dp[u][1] = 0;
int f = 0;
for (int i = head[u]; i != -1; i = E[i].next){
int v = E[i].v;
if (v == pre) continue;
f = 1;
tree_dp(v, u);
for (int j = k; j >= 0; j--){
for (int t = 1; t <= j; t++)
cmin(dp[u][j], dp[u][j - t] + dp[v][t] + E[i].w * t * (k - t) * 2);
}
}
}
int main(){
int u, v, w, T;
scanf("%d", &T);
while (T--){
scanf("%d %d", &n, &k);
Init();
for (int i = 1; i < n; i++){
scanf("%d %d %d", &u, &v, &w);
add_edge(u, v, w);
add_edge(v, u, w);
}
tree_dp(1, -1);
cout << dp[1][k] << endl;
}
return 0;
}
/*
1
2 2
1 2 1
*/