您的位置:首页 > 移动开发

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息