URAL 1018 Binary Apple Tree (树形DP)
2015-10-22 17:09
344 查看
#include <stdio.h> #define MAX_POINTS 100 #define MAX(x, y) ( (x) > (y) ? (x) : (y) ) typedef struct Branch{ int to; int apples; int next; }Branch; Branch BranchArray[MAX_POINTS * 2]; int BranchNum; int head[MAX_POINTS + 1]; int branches[MAX_POINTS + 1]; //maxApple[point][preBranches]表示点point的前preBreanches个枝干branch的最大苹果数,其中包含从point的根节点到point的枝干上的苹果数 int maxApples[MAX_POINTS + 1][MAX_POINTS + 1]; int numOfPoints, numOfBranchesPreserved; void addBranch(int from, int to, int apples){ BranchNum++; BranchArray[BranchNum].to = to; BranchArray[BranchNum].apples = apples; BranchArray[BranchNum].next = head[from]; head[from] = BranchNum; } void dfs(int fromParent, int from){ //from的branches包含从fromParent到from的枝干 branches[from] = 1; int i, to, apples; //for i,只会循环两次,一次左孩子,一次右孩子 for (i = head[from]; i != 0; i = BranchArray[i].next){ to = BranchArray[i].to; if (to == fromParent) continue; dfs(from, to); branches[from] += branches[to]; apples = BranchArray[i].apples; int preFromBranches, preToBranches; for (preFromBranches = branches[from]; preFromBranches >= 1; preFromBranches--) //注意preToBranches不能等于preFromBranches,因为还有从from到to分支上的apples for (preToBranches = 1; preToBranches < preFromBranches && preToBranches <= branches[to]; preToBranches++) //当to为右孩子的时候,下面是执行左右孩子分支的比较 maxApples[from][preFromBranches] = MAX(maxApples[from][preFromBranches], maxApples[from][preFromBranches - preToBranches] + maxApples[to][preToBranches] + apples); } } int main(){ //freopen("input.txt", "r", stdin); scanf("%d%d", &numOfPoints, &numOfBranchesPreserved); int from, to, apples; numOfPoints--; while (numOfPoints--){ scanf("%d%d%d", &from, &to, &apples); addBranch(from, to, apples); addBranch(to, from, apples); } dfs(-1, 1); printf("%d\n", maxApples[1][numOfBranchesPreserved + 1]); return 0; }
相关文章推荐
- jquery+CSS实现的多级竖向展开树形TRee菜单效果
- cmd tree命令 以树形格式罗列文件
- JS+CSS简单树形菜单实现方法
- JS+CSS实现TreeMenu二级树形菜单完整实例
- 基于jquery实现的树形菜单效果代码
- 推荐8款jQuery轻量级树形Tree插件
- asp.net 获取指定文件夹下所有子目录及文件(树形)
- javascript 树形导航菜单实例代码
- js树形控件脚本代码
- 基于递归实现的php树形菜单代码
- 基于Android中dp和px之间进行转换的实现代码
- Android中dip、dp、sp、pt和px的区别详解
- json+jQuery实现的无限级树形菜单效果代码
- php实现的树形结构数据存取类实例
- javascript实现树形菜单的方法
- js实现无限级树形导航列表效果代码
- LFC1.0.0 版本发布
- 树形数据表设计(转)
- Android px、dp、sp之间相互转换
- android中像素单位dp、px、pt、sp的比较