Timus 1018 Binary Apple Tree
2013-04-07 21:17
295 查看
http://acm.timus.ru/problem.aspx?space=1&num=1018
类型:树dp
AC Code
类型:树dp
AC Code
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int a[105][105],val[105]={0},tree[105][3],f[105][105],n; void buildtree(int root) { int lr=0; for(int i=1;i<=n;i++) if(a[root][i]>0){ if(lr==2) return; lr++; tree[root][lr]=i; val[i]=a[root][i]; a[i][root]=-1; buildtree(i); } } void dfs(int root,int num) { if(num==0){ f[root][num]=0; return; } else if(tree[root][1]==0&&tree[root][2]==0){ f[root][num]=val[root]; return; } else{ for(int i=0;i<num;i++){ if(f[tree[root][1]][i]==0)dfs(tree[root][1],i); if(f[tree[root][2]][num-1-i]==0)dfs(tree[root][2],num-1-i); f[root][num]=max(f[root][num],f[tree[root][1]][i]+f[tree[root][2]][num-1-i]+val[root]); //if(root==1&&num==3) //printf("f=%d\n",f[1][3]); } } } void print() { for(int i=1;i<6;i++) printf("%d %d \n",tree[i][1],tree[i][2]); printf("\n"); for(int i=1;i<6;i++) printf("%d\n",val[i]); printf("\n"); } int main() { int m; scanf("%d%d",&n,&m); memset(a,0,sizeof(a)); memset(val,0,sizeof(val)); memset(f,0,sizeof(f)); memset(tree,0,sizeof(tree)); for(int i=1;i<n;i++){ int xx,yy,val; scanf("%d%d%d",&xx,&yy,&val); a[xx][yy]=val; a[yy][xx]=val; } buildtree(1); //print(); dfs(1,m+1); printf("%d\n",f[1][m+1]); return 0; }
相关文章推荐
- ural 1018 Binary Apple Tree
- Ural_1018. Binary Apple Tree(树形DP)
- URAL 1018 Binary Apple Tree
- URAL 1018. Binary Apple Tree(树形DP)
- CJOJ 1976 二叉苹果树 / URAL 1018 Binary Apple Tree
- URAL1018 Binary Apple Tree
- ural 1108 Binary Apple Tree
- Timus Online Judge 1018 Binary Apple Tree(树型dp)
- Binary Apple Tree
- URAL1018 Binary Apple Tree(树dp)
- [LeetCode] Flatten Binary Tree to Linked List
- [LeetCode] Validate Binary Search Tree
- 236. Lowest Common Ancestor of a Binary Tree
- leetcode235. Lowest Common Ancestor of a Binary Search Tree
- 637. Average of Levels in Binary Tree
- Flatten Binary Tree to Linked List(leetcode)
- Validate Binary Search Tree
- [lintcode] Binary Tree Maximum Path Sum II
- leetcode.107.Binary Tree Level Order Traversal II
- Leetcode-236. Lowest Common Ancestor of a Binary Tree 最小公共祖先