题目:http://acm.hdu.edu.cn/showproblem.php?pid=4003
View Code
#include <stdio.h> #include <string.h> #include <algorithm> #define clr(a,b) memset(a,b,sizeof(a)) using namespace std; const int N = 10000+10; const int M = 20000+10; int n, e, s, k; int he[N]; int ev[M], ew[M], nxt[M]; int dp[N][11]; void init() { e = 0; clr(he, -1); } void add(int u, int v, int w) { ev[e]=v; ew[e]=w; nxt[e]=he[u]; he[u]=e++; ev[e]=u; ew[e]=w; nxt[e]=he[v]; he[v]=e++; } void dfs(int u, int r) { for (int i=he[u]; i!=-1; i=nxt[i]) { if (ev[i] == r)continue; dfs(ev[i], u); } for (int i=he[u]; i!=-1; i=nxt[i]) { int v = ev[i]; if (v == r)continue; for (int j=k; j>=0; j--) { dp[u][j]+=dp[v][0]+2*ew[i]; for (int t=1; t<=j; t++) dp[u][j]=min(dp[u][j], dp[u][j-t]+dp[v][t]+t*ew[i]); } } } int main() { //freopen("D:/a.txt", "r", stdin); while (~scanf("%d%d%d", &n, &s, &k)) { init(); for (int i=1; i<n; i++) { int u, v, w; scanf("%d%d%d", &u, &v, &w); add(u, v, w); } clr(dp, 0); dfs(s, 0); printf("%d\n", dp[s][k]); } return 0; }