Portal
Analysis
A simple tree DP, we use the dp[i][j] record to consider the point I, preserving the maximum number of J branches, and then DFS solver.
Code
#include <iostream>#include<cstdio>#include<cstring>#include<string>#include<algorithm>#include<cctype>#include<cmath>#include<cstdlib>#include<queue>#include<ctime>#include<vector>#include<Set>#include<map>#include<stack>using namespacestd;#definePB Push_back#defineMP Make_pairVector<pair<int,int> >v[ the];p Air<int,int>son[2][ the];intdp[ the][ the],n,m;inlinevoidDfsintXintFA) { intcnt=-1; for(intI=0; I<v[x].size (); i++) if(v[x][i].first!=FA) {son[++cnt][x]=V[x][i]; DFS (V[X][I].FIRST,X); } return;} InlinevoidGETDP (intx) { if(!son[0][x].first)return; GETDP (son[0][x].first); GETDP (son[1][x].first); for(intI=0; i<n-2; i++) for(intj=0; j<=i;j++) Dp[x][i+2]=max (dp[x][i+2],dp[son[0][x].first][j]+dp[son[1][x].first][i-j]+son[0][x].second+son[1][x].second); for(intI=0; i<n-1; i++) for(intj=0; j<=i;j++) Dp[x][i+1]=max (dp[x][i+1],max (dp[son[0][x].first][j]+son[0][x].second,dp[son[1][x].first][i-j]+son[1][x].second)); return;} intMain () {intI,j,k,x,y; scanf ("%d%d",&n,&m); for(i=1; i<n;i++) {scanf ("%d%d%d",&x,&y,&k); V[X].PB (MP (Y,K)); V[Y].PB (MP (X,K)); } memset (DP,0,sizeof(DP)); DFS (1,0); GETDP (1); printf ("%d\n", dp[1][m]); return 0;}
loj10153 two-prong apple tree