Tree-shaped DP

Source: Internet
Author: User

To a tree with a node right, find a subtree with K nodes, and seek the maximum weight of this subtree.

Dp[u][k] represents the maximum weight of a subtree with a U-node that has a size of k in the root of U, and

Then make a group backpack for each child node of U, because for each son of U, you can choose to assign
1,2,3...k-1 a node to it

State transition equation:

When the node size is k, it can be by the root node is U, the subtree size is k-t, plus the root node is V, the subtree size is T the state transfer (V is a child of u), that is:


Dp[u][k] = max (Dp[u][k], dp[u][k-t]+dp[v][t]);//v is the son of U node

#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<vector>using namespacestd;//simple tree-shaped DPintMaxintAintb) {    returnA>b?a:b;}Const intINF =1<< -;intn,k;intx[202];intdp[202][202];vector<int> list[202];voidDfsintUintfather) {    inti,j;  for(i=0; I<list[u].size (); i++)    {        intv=List[u][i]; if(v==father)Continue;                DFS (V,U);  for(j=k;j>=1; j--)//must be reversed .        {             for(intt=1; t<=j;t++) Dp[u][j]=max (Dp[u][j], dp[u][t]+dp[v][j-T]); }    }}intMain () {scanf ("%d%d",&n,&k); inti,j,a,b;  for(i =0; I <= n;i++)//Empty List Tablelist[i].clear (); Memset (DP,0,sizeof(DP)); dp[0][1]=0;//maximum weight with 0 nodes and only 1 words in the root node     for(i=1; i<=n;i++) {scanf ("%d%d", &b,&dp[i][1]);//maximum weight with I as the root node with only 1 words in the nodeList[i].push_back (b);    List[b].push_back (i); } k++;//Add a 0 nodeDfs0,-1); printf ("%d\n", dp[0][k]);//maximum weight with 0 for the root node and only the number of words in M nodes    return 0;}

Tree-shaped DP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.