Question Link: Http://acm.hust.edu.cn/vjudge/problem/viewProblem.action? Id = 17662
Theme: The branches are connected with a lump of Apples (don't care about 'lump '). Given that M branches are left, ask the maximum number of apples left at the end.
Solutions:
In fact, the meaning is similar to that of vijos 1180 (Course Selection. Only the right is on the edge.
First, create an undirected graph DFS.
For (F + 1... j... cost)
For (1... k... j-cost)
F indicates the number of DFS subnodes. The reason for the addition of 1 is that the current vertex also needs to be allocated a branch to get the apple of This vertex.
F + = DFS (t), DFS (t) returns the F + 1 of the Child vertex T.
In fact, F + 1 can be directly written as m + 1, but it takes many unnecessary loops.
The final result is DP [1] [M + 1]. Note that because of the tree structure, the apple on 1 can be obtained by default, but in this DP mode, the apple on 1 should be obtained, you also need to add a virtual branch, that is, Why m + 1.
#include "cstdio"#include "queue"#include "iostream"#include "cstring"using namespace std;#define maxn 105int n,m,dp[maxn][maxn],head[maxn],tol;struct Edge{ int next,to,w;}e[maxn*2];void addedge(int u,int v,int w){ e[tol].to=v; e[tol].next=head[u]; e[tol].w=w; head[u]=tol++;}int dfs(int root,int pre){ int cost=1,i=root,f=0; for(int a=head[root];a!=-1;a=e[a].next) { int t=e[a].to; if(t==pre) continue; f+=dfs(t,root); for(int j=f+1;j>=1;j--) for(int k=1;k<=j-cost;k++) dp[i][j]=max(dp[i][j],dp[i][j-k]+dp[t][k]+e[a].w); } return f+cost;}int main(){ //freopen("in.txt","r",stdin); int u,v,w; scanf("%d%d",&n,&m); memset(head,-1,sizeof(head)); for(int i=1;i<n;i++) { scanf("%d%d%d",&u,&v,&w); addedge(u,v,w); addedge(v,u,w); } dfs(1,1); printf("%d\n",dp[1][m+1]);}
2867777 |
Neopenx |
Ural |
1018 |
Accepted |
418 |
31 |
G ++ 4.9 |
917 |
2014-10-20 16:15:45 |
Ural 1018 (tree DP + backpack + optimization)