URAL 1018 Binary Apple Tree (树形DP)

#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的最大苹果数
int maxApples[MAX_POINTS + 1][MAX_POINTS + 1];
int visited[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){
int leftChild = 0;
int rightChild = 0;
int leftApples = 0;
int rightApples = 0;
int i;
for (i = head[from]; i != 0; i = BranchArray[i].next){
if (BranchArray[i].to == fromParent)
continue;
if (leftChild == 0){
leftChild = BranchArray[i].to;
leftApples = BranchArray[i].apples;
if (visited[leftChild] == 0){
visited[leftChild] = 1;
dfs(from, leftChild);
}
} else {
rightChild = BranchArray[i].to;
rightApples = BranchArray[i].apples;
if (visited[rightChild] == 0){
visited[rightChild] = 1;
dfs(from, rightChild);
}
}
}

//只有一个枝干的情况,左枝干或者右枝干
maxApples[from][1] = MAX(leftApples, rightApples);


int temp = leftApples + rightApples;


int j;
for (i = 2; i <= numOfBranchesPreserved; i++){
//枝干全在左边,或者全在右边
maxApples[from][i] = MAX(maxApples[leftChild][i - 1] + leftApples, maxApples[rightChild][i - 1] + rightApples);
for (j = 0; j <= i - 2; j++)
//一边至少有一个枝干
maxApples[from][i] = MAX(maxApples[from][i], maxApples[leftChild][j] + maxApples[rightChild][i - 2 - j] + temp);
}


}


int main(){


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);
}


visited[1] = 1;
dfs(-1, 1);


printf("%d\n", maxApples[1][numOfBranchesPreserved]);


return 0;
}

你可能感兴趣的:(apple,dp,tree,binary,树形,1018,ural)