hdu 4616 Game

树dp,学了一招,以边进行dp

#include <stdio.h>
#include <vector>
#include <string.h>
using namespace std;
#define MAXN 50010
int trap[MAXN], gift[MAXN], n, c, ans;
int dp[MAXN<<1][5], head[MAXN], cnt;
struct _edge
{
	int u, v, next;
	_edge(int uu = 0, int vv = 0, int nn = 0):u(uu),v(vv),next(nn){}
}edge[MAXN<<1];
void add (int u, int v)
{
	edge[cnt] = _edge(u,v,head[u]);
	memset(dp[cnt], -1, 20);
	head[u] = cnt++;
}
int dfs(int dx, int tp)
{
	if (tp == c ) return 0;
	if (~dp[dx][tp]) return dp[dx][tp];
	int u = edge[dx].u;
	int v = edge[dx].v;
	int res = gift[v];
	int a = tp + trap[v];
	for (int i = head[v]; ~i; i = edge[i].next)
	{
		if (edge[i].v == u) continue;
		res = max(res, gift[v]+dfs(i, a));
	}
	return dp[dx][tp] = res;
}
int main()
{
#ifdef  __GNUC__
    freopen ( "in.txt", "r", stdin );
#endif // __GNUC__
    int t;
    scanf("%d", &t);
    while (t--)
	{
		scanf("%d%d", &n, &c);
		for (int i = 0; i< n; ++i)
		{
			scanf("%d%d", &gift[i], &trap[i]);
			head[i] = -1;
		}
		cnt = 0;
		for (int i = 1; i< n; ++i)
		{
			int a, b;
			scanf("%d%d", &a, &b);
			add(a, b);
			add(b, a);
		}
		ans = 0;
		for (int i = 0; i< cnt; ++i)
		{
			int u = edge[i].u;
			ans = max(ans, gift[u]+dfs(i,trap[u]));
		}
		printf("%d\n", ans);
	}
    return 0;
}





你可能感兴趣的:(hdu 4616 Game)