标签:
这道题可以和POJ 2486 树形背包DP Apple Tree比较着来做。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <vector> 6 using namespace std; 7 8 const int maxn = 500 + 10; 9 10 int n, Q; 11 vector<int> G[maxn], C[maxn]; 12 13 int d[maxn][maxn][2], cnt[maxn]; 14 15 void dfs(int u) 16 { 17 cnt[u] = 1; 18 d[u][1][0] = d[u][1][1] = 0; 19 for(int i = 0; i < G[u].size(); i++) 20 { 21 int v = G[u][i]; 22 int w = C[u][i]; 23 dfs(v); 24 cnt[u] += cnt[v]; 25 26 for(int j = cnt[u]; j >= 2; j--) 27 for(int x = 0; x <= j && x <= cnt[v]; x++) 28 { 29 d[u][j][0] = min(d[u][j][0], d[v][x][0] + d[u][j-x][0] + w * 2); 30 d[u][j][1] = min(d[u][j][1], d[v][x][0] + d[u][j-x][1] + w * 2); 31 d[u][j][1] = min(d[u][j][1], d[v][x][1] + d[u][j-x][0] + w); 32 } 33 } 34 } 35 36 int main() 37 { 38 int kase = 1; 39 while(scanf("%d", &n) == 1 && n) 40 { 41 for(int i = 0; i < n; i++) { G[i].clear(); C[i].clear(); } 42 for(int i = 1; i < n; i++) 43 { 44 int a, b, d; scanf("%d%d%d", &a, &b, &d); 45 G[b].push_back(a); C[b].push_back(d); 46 } 47 48 memset(d, 0x3f, sizeof(d)); 49 dfs(0); 50 51 printf("Case %d:\n", kase++); 52 scanf("%d", &Q); 53 while(Q--) 54 { 55 int x; scanf("%d", &x); 56 int ans; 57 for(ans = n; ans > 0; ans--) if(d[0][ans][1] <= x) break; 58 printf("%d\n", ans); 59 } 60 } 61 62 return 0; 63 }
标签:
原文地址:http://www.cnblogs.com/AOQNRMGYXLMV/p/4701127.html