题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1018
Dynamic Programming. 首先要根据input建立树形结构,然后在用DP来寻找最佳结果。dp[i][j]表示node i的子树上最多保存j个分支的最佳结果。代码如下:
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <cstdio>
#include <algorithm>
#include <string.h>
#include <string>
#include <sstream>
#include <cstring>
#include <queue>
#include <vector>
#include <functional>
#include <cmath>
#include <set>
#define SCF(a) scanf("%d", &a)
#define IN(a) cin>>a
#define FOR(i, a, b) for(int i=a;i<b;i++)
#define Infinity 9999999
typedef long long Int;
using namespace std; int dp[][]; //row -> node id, col -> branches preserved. struct link {
int parent;
int child;
int weight;
}; struct tree {
int parent;
tree *left, *right;
int leftw, rightw;
}; int N, Q;
link links[];
bool visited[]; tree * construct(int pid)
{
tree *t = new tree;
t->parent = pid;
int num = ;
bool found = false;
FOR(i, , N - )
{
if (visited[i] == false && (links[i].parent == pid || links[i].child==pid))
{
visited[i] = true;
if (num == )
{
t->leftw = links[i].weight;
if(links[i].parent==pid)
t->left = construct(links[i].child);
else
t->left = construct(links[i].parent);
num++;
}
else if (num == )
{
t->rightw = links[i].weight;
if(links[i].parent==pid)
t->right = construct(links[i].child);
else
t->right = construct(links[i].parent);
found = true;
break;
}
}
}
if (found == false)
{
t->left = NULL;
t->right = NULL;
}
return t;
} int calcuTree(tree *t, int R)
{
if (t == NULL)
return ; int id = t->parent;
if (dp[id][R] == -)
{
int maxLeft = ;
for (int leftR = ; leftR <= R; leftR++)
{
int cleft = ;
int rightR = R - leftR;
if (leftR > )
{
cleft += t->leftw;
cleft += calcuTree(t->left, leftR - );
}
if (rightR > )
{
cleft += t->rightw;
cleft += calcuTree(t->right, rightR - );
} if (cleft > maxLeft)
maxLeft = cleft;
}
dp[id][R] = maxLeft;
}
return dp[id][R];
} int main()
{
while (scanf("%d %d\n", &N, &Q) != EOF)
{
FOR(i, , N - )
{
int p, c, w;
scanf("%d %d %d", &links[i].parent, &links[i].child, &links[i].weight);
} FOR(i, , N - )
visited[i] = false; tree *t = new tree;
t = construct(); FOR(i, , N + )
{
FOR(j, , Q + )
{
dp[i][j] = -;
}
} FOR(i, , N + )
{
dp[i][] = ;
} int ans = calcuTree(t, Q);
printf("%d\n", ans);
}
return ;
}