码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1561 树形dp

时间:2015-07-18 21:11:57      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

又一道树形dp,发现其实树形dp长得都挺像的。

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 using namespace std;
 5 
 6 const int INF = -9999999;
 7 const int N = 201;
 8 int dp[N][N];
 9 int head[N];
10 int value[N];
11 int n, m, e;
12 
13 void init()
14 {
15     e = 0;
16     memset( head, -1, sizeof(head) );
17 }
18 
19 struct Edge
20 {
21     int v, next;
22 } edge[N];
23 
24 void addEdge( int u, int v )
25 {
26     edge[e].v = v;
27     edge[e].next = head[u];
28     head[u] = e++;
29 }
30 
31 void dfs( int u )
32 {
33     dp[u][1] = value[u];
34     for ( int i = 2; i <= m + 1; i++ )
35     {
36         dp[u][i] = INF;
37     }
38     for ( int i = head[u]; i != -1; i = edge[i].next )
39     {
40         int v = edge[i].v;
41         dfs(v);
42         for ( int j = m + 1; j > 1; j-- )
43         {
44             for ( int k = 1; k < j; k++ )
45             {
46                 dp[u][j] = max( dp[u][j], dp[u][j - k] + dp[v][k] );
47             }
48         }
49     }
50 }
51 
52 int main ()
53 {
54     while ( scanf("%d%d", &n, &m) != EOF )
55     {
56         if ( n == 0 && m == 0 ) break;
57         init();
58         value[0] = 0;
59         for ( int i = 1; i <= n; i++ )
60         {
61             int tmp;
62             scanf("%d%d", &tmp, value + i);
63             addEdge( tmp, i );
64         }
65         dfs(0);
66         printf("%d\n", dp[0][m + 1]);
67     }
68     return 0;
69 }

 

hdu 1561 树形dp

标签:

原文地址:http://www.cnblogs.com/huoxiayu/p/4657506.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!