【树形DP】P2015 二叉苹果树

 1 #include<iostream>
 2 #include<string>
 3 #include<queue>
 4 #include<stack>
 5 #include<vector>
 6 #include<map>
 7 #include<cstdio>
 8 #include<cstdlib>
 9 #include<algorithm>
10 #include<set>
11 #include<list>
12 #include<iomanip>
13 #include<cstring>
14 #include<cmath>
15 #include<limits>
16 using namespace std;
17 
18 #define au auto
19 #define debug(i) cout<<"<debug> "<<i<<"<\debug>"<<endl
20 #define mfor(i,a,b) for(register int i=(a);i<=(b);i++)
21 #define mrep(i,a,b) for(register int i=(a);i>=(b);i--)
22 #define LLL __int128
23 #define Re register
24 #define il inline
25 #define mem(a,b) memset(a,(b),sizeof(a))
26 typedef pair<int, int> intpair;
27 typedef long long int LL;
28 const int INF = 0x3f3f3f3f;
29 const long long int INFLL = 0x3f3f3f3f3f3f3f3f;
30 
31 int cnt;
32 const int maxn = 10010;
33 int n, m;
34 int f[maxn][maxn];
35 int num[maxn];
36 
37 struct Edge
38 {
39     int u, nxt;
40     int w;
41 }e[maxn];
42 
43 int head[maxn];
44 
45 void add(int a, int b, int w)
46 {
47     e[++cnt].u = b;
48     e[cnt].nxt = head[a];
49     head[a] = cnt;
50     e[cnt].w = w;
51 }
52 
53 void dfs(int x, int fa)
54 {
55     for (Re int i = head[x]; i != -1; i = e[i].nxt)
56     {
57         int u = e[i].u;
58         if (u == fa) continue;
59         dfs(u, x);
60         num[x] += num[u] + 1;
61         mrep(j, min(num[x], m), 0)
62         {
63             mrep(k, min(num[u], j - 1), 0)
64             {
65                 f[x][j] = max(f[x][j], f[x][j - k - 1] + f[u][k] + e[i].w);
66             }
67         }
68     }
69 }
70 
71 int main()
72 {
73     ios::sync_with_stdio(0);
74     cin.tie(0);
75     mem(head, -1);
76     cin >> n >> m;
77     mfor(i, 1, n - 1)
78     {
79         Re int a, b, c;
80         cin >> a >> b >> c;
81         add(a, b, c);
82         add(b, a, c);
83     }
84     dfs(1, INF);
85     cout << f[1][m];
86 }
View Code

 

posted on 2019-10-23 18:45  thjkhdf12  阅读(105)  评论(0)    收藏  举报