URAL 1039. Anniversary Party(树形DP)
从早上就开始写,开始一直徘徊在递归的死循环,递归部分竟然不知如何实现了,后来写了个很暴力方法。。。建树还是左孩子,右兄弟,这个题这样写反而不怎么方便(效率也低了?),在 所有儿子的和 和本身+孙子的和 取大,递归部分写的很麻烦,导致先是WA在第7组(看DISUSS知道了数据),某一个小地方敲错了,然后又挂在13组上了,又改了一个BUG,然后还是WA,原来是要注意负数情况。。。纠结不知道怎么改,乱搞了一下,改初始化 + 和0比较,终于过了。。。
建树建的不好,导致写的很麻烦,效率也很搓。
1 #include <stdio.h> 2 #include <string.h> 3 #define INF -2139062144 4 struct node 5 { 6 int left,right; 7 }; 8 struct node tree[6001]; 9 int p[6001],o[6001],key[6001]; 10 int max(int a,int b) 11 { 12 return a > b? a:b; 13 } 14 void insert(int son,int father) 15 { 16 int t; 17 if(tree[father].left == -1) 18 { 19 tree[father].left = son; 20 } 21 else 22 { 23 t = tree[father].left; 24 while(tree[t].right != -1) 25 { 26 t = tree[t].right; 27 } 28 tree[t].right = son; 29 } 30 return ; 31 } 32 int dp(int x) 33 { 34 int t,sum,v; 35 if(key[x] > INF) 36 { 37 if(key[x] < 0) 38 return 0; 39 else 40 return key[x]; 41 } 42 if(x == -1) 43 { 44 return 0; 45 } 46 t = tree[x].left; 47 if(t != -1) 48 { 49 key[x] = dp(t); 50 v = tree[t].right; 51 while(v != -1) 52 { 53 key[x] += dp(v); 54 v = tree[v].right; 55 } 56 } 57 sum = p[x]; 58 while(t != -1) 59 { 60 if(tree[t].left != -1) 61 { 62 sum += dp(tree[t].left); 63 v = tree[tree[t].left].right; 64 while(v != -1) 65 { 66 sum += dp(v); 67 v = tree[v].right; 68 } 69 } 70 t = tree[t].right; 71 } 72 key[x] = max(key[x],sum); 73 if(key[x] < 0) 74 return 0; 75 else 76 return key[x]; 77 } 78 int main() 79 { 80 int i,n,fa,so; 81 scanf("%d",&n); 82 memset(tree,-1,sizeof(tree)); 83 memset(key,128,sizeof(key)); 84 for(i = 1; i <= n; i ++) 85 { 86 scanf("%d",&p[i]); 87 } 88 for(;;) 89 { 90 scanf("%d%d",&so,&fa); 91 if(!so&&!fa) break; 92 o[so] = 1; 93 insert(so,fa); 94 } 95 for(i = 1; i <= n; i ++) 96 { 97 if(!o[i]) 98 insert(i,0); 99 } 100 printf("%d\n",dp(tree[0].left)); 101 return 0; 102 } 103 /* 104 8 105 5 106 1 107 1 108 1 109 1 110 1 111 1 112 1 113 2 1 114 3 1 115 4 1 116 5 1 117 6 1 118 7 1 119 8 1 120 0 0 121 11 122 5 123 4 124 3 125 2 126 7 127 1 128 1 129 1 130 1 131 1 132 1 133 6 4 134 7 4 135 8 4 136 9 5 137 10 5 138 11 5 139 4 3 140 5 3 141 3 2 142 2 1 143 0 0 144 */