RQNOJ 30 愚蠢的矿工 解题报告
树形动态规划,第一次接触这样的树形动态规划,应该说是彻底的,以前的那个什么没有上司的舞会都是小儿科,嗯,思路见网上同类报告(偷懒)
代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> int num[1001]; struct node{ int left, right; int sum; }tree[1001]; int f[1002][102]; int m, n; int srch(int root, int count) { int i; int t; if(f[root][count] != 0){ return f[root][count]; } if(tree[root].right != n + 1){ f[root][count] = srch(tree[root].right, count); } for(i = 0; i < count; i++){ t = srch(tree[root].left, i) + srch(tree[root].right, count - i - 1) + num[root]; if(f[root][count] < t){ f[root][count] = t; } } return f[root][count]; } int main(int argc, char **argv) { int i, j; int a, b; scanf("%d%d", &n, &m); tree[0].left = tree[0].right = n + 1; for(i = 1; i <= n; i++){ tree[i].left = tree[i].right = n + 1; scanf("%d", &num[i]); } for(i = 1; i <= n; i++){ scanf("%d%d", &a, &b); if(tree[a].left == n + 1){ tree[a].left = b; }else{ j = tree[a].left; while(tree[j].right != n + 1){ j = tree[j].right; } tree[j].right = b; } } for(i = 1; i <= m + 1; i++){ f[n + 1][i] = -1000000; } printf("%d\n", srch(0, m + 1)); return 0; }