| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 7784 | Accepted: 2603 |
Description
Input
Output
Sample Input
2 1
0 11
1 2
3 2
0 1 2
1 2
1 3
Sample Output
11
2
Source
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
int const MAX = 205;
vector <int> t[MAX];
int dp[MAX][MAX][2], val[MAX];
int n, m;
bool vis[MAX];
void DFS(int u)
{
vis[u] = true;
for(int i = 0; i <= m; i++)
dp[u][i][0] = dp[u][i][1] = val[u]; //从u出发至少可以获得val[u]个
int len = t[u].size();
for(int i = 0; i < len; i++)
{
int v = t[u][i];
if(!vis[v])
{
DFS(v);
for(int j = m; j >= 0; j--)
{
for(int k = 0; k <= j; k++)
{
dp[u][j + 2][1] = max(dp[u][j + 2][1], dp[u][k][1] + dp[v][j - k][1]);
dp[u][j + 1][0] = max(dp[u][j + 1][0], dp[u][k][1] + dp[v][j - k][0]);
dp[u][j + 2][0] = max(dp[u][j + 2][0], dp[u][k][0] + dp[v][j - k][1]);
}
}
}
}
}
int main()
{
while(scanf("%d %d", &n, &m) != EOF)
{
memset(dp, 0, sizeof(dp));
memset(vis, false, sizeof(vis));
for(int i = 1; i <= n; i++)
{
scanf("%d", &val[i]);
t[i].clear();
}
for(int i = 1; i < n; i++)
{
int u, v;
scanf("%d %d", &u, &v);
t[u].push_back(v);
t[v].push_back(u);
}
DFS(1);
printf("%d\n", dp[1][m][0]);
}
}#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int const MAX = 205;
int dp[MAX][MAX][2], val[MAX];
int head[MAX], cnt;
int n, m;
struct Edge
{
int to, next;
}e[MAX * MAX / 2];
void Add(int x, int y)
{
e[cnt].to = y;
e[cnt].next = head[x];
head[x] = cnt++;
}
void DFS(int u, int fa)
{
for(int i = 0; i <= m; i++)
dp[u][i][0] = dp[u][i][1] = val[u];
for(int i = head[u]; i != -1; i = e[i].next)
{
int v = e[i].to;
if(v != fa)
{
DFS(v, u);
for(int j = m; j >= 0; j--)
{
for(int k = 0; k <= j; k++)
{
dp[u][j + 2][1] = max(dp[u][j + 2][1], dp[u][k][1] + dp[v][j - k][1]);
dp[u][j + 1][0] = max(dp[u][j + 1][0], dp[u][k][1] + dp[v][j - k][0]);
dp[u][j + 2][0] = max(dp[u][j + 2][0], dp[u][k][0] + dp[v][j - k][1]);
}
}
}
}
}
int main()
{
while(scanf("%d %d", &n, &m) != EOF)
{
cnt = 0;
memset(dp, 0, sizeof(dp));
memset(head, -1, sizeof(head));
for(int i = 1; i <= n; i++)
scanf("%d", &val[i]);
for(int i = 1; i < n; i++)
{
int u, v;
scanf("%d %d", &u, &v);
Add(u, v);
Add(v, u);
}
DFS(1, -1);
printf("%d\n", dp[1][m][0]);
}
}POJ 2486 Apple Tree (树形dp 经典题)
原文地址:http://blog.csdn.net/tc_to_top/article/details/44194303