Game
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 1435 Accepted Submission(s): 451
Problem Description
Nowadays, there are more and more challenge game on TV such as 'Girls, Rush Ahead'. Now, you participate int a game like this. There are N rooms. The connection of rooms is like a tree. In other words, you can go to any other room by one and only one way. There is a gift prepared for you in Every room, and if you go the room, you can get this gift. However, there is also a trap in some rooms. After you get the gift, you may be trapped. After you go out a room, you can not go back to it any more. You can choose to start at any room ,and when you have no room to go or have been trapped for C times, game overs. Now you would like to know what is the maximum total value of gifts you can get.
Input
The first line contains an integer T, indicating the number of testcases.
For each testcase, the first line contains one integer N(2 <= N <= 50000), the number rooms, and another integer C(1 <= C <= 3), the number of chances to be trapped. Each of the next N lines contains two integers, which are the value of gift in the room and whether have trap in this rooom. Rooms are numbered from 0 to N-1. Each of the next N-1 lines contains two integer A and B(0 <= A,B <= N-1), representing that room A and room B is connected.
All gifts' value are bigger than 0.
Output
For each testcase, output the maximum total value of gifts you can get.
Sample Input
2
3 1
23 0
12 0
123 1
0 2
2 1
3 2
23 0
12 0
123 1
0 2
2 1
Sample Output
Source
2013 Multi-University Training Contest 2
Recommend
zhuyuanchen520
题意:
给一棵树,每个结点中有礼物,每个礼物有一个权值,某些结点中会有陷阱,你可以从任何一点出发,每个结点最多只能经过一次,最多掉进陷阱C次,求出可获得的礼物的最大值。
思路:
开始没理解。理解后发现其实很简单。不用树形DP直接对边DP就行了。对于每条边只有走或不走两种情况。
我们只要把每条边处理下就行了。
用dp[id][i]表示到达id这条所连的儿子已经经过i个陷阱的最大礼物值。
那么dp[id][i]=max(dp[v][i+
track[v]
]+val[u])。v为u的儿子。然后记忆化dp就行了。
详细见代码:
#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxn=50050;
struct node
{
int u,v;
int next;
} edge[maxn<<1];
int head[maxn];
int val[maxn],track[maxn],dp[maxn<<1][5];
int ptr,n,c,ans;
void adde(int u,int v)
{
edge[ptr].v=v;
edge[ptr].u=u;
edge[ptr].next=head[u];
head[u]=ptr++;
}
int dfs(int id,int tra)
{
if(tra==c)//陷阱数已达上限
return 0;
if(dp[id][tra]!=-1)
return dp[id][tra];
int u,v,p,t,best;
u=edge[id].u;
v=edge[id].v;
best=val[v];
t=tra+track[v];
for(p=head[v]; p!=-1; p=edge[p].next)
if(edge[p].v!=u)
best=max(best,dfs(p,t)+val[v]);
return dp[id][tra]=best;
}
int main()
{
int i,u,v,cas;
scanf("%d",&cas);
while(cas--)
{
scanf("%d%d",&n,&c);
memset(head,-1,sizeof head);
memset(dp,-1,sizeof dp);
ptr=0;
for(i=0; i<n; i++)
scanf("%d%d",val+i,track+i);
for(i=1; i<n; i++)
{
scanf("%d%d",&u,&v);
adde(u,v);
adde(v,u);
}
ans=0;
for(i=0; i<ptr; i++)
{
u=edge[i].u;
ans=max(ans,dfs(i,track[u])+val[u]);
}
printf("%d\n",ans);
}
return 0;
}