标签:
又一道树形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 }
标签:
原文地址:http://www.cnblogs.com/huoxiayu/p/4657506.html