Binary apple (by a root into the left subtree and right subtree some cases two)

There are a binary apple tree, if there is bifurcation digital, it must be bifurcated, that there is only one son node. This tree total   nodes, labels   to  , to a certain number roots  .

We use a branch node connected to both ends of a branch number description position. There are four branches of an apple tree because the branches are too many, need pruning. But some of the branches grow apples, given the need to retain a number of branches, seeking to keep up to how many apples.

tree.png

Input Format

The first two row number N and Q , N  represents the number of nodes of the tree,  Q represents the number of branches to be retained.

Then N-1 line description information of branches, three integers each row, the first two is the number of nodes connected to it, the third number is the number of the limb and apples.

Output Format

Output only one line, represents the number of up to keep the apple.


 

f [i] [j] indicates that the current node retain the maximum number of Apple j twig

 

#include<bits/stdc++.h> 
#define re return
#define inc(i,l,r) for(int i=l;i<=r;++i)
using namespace std;
template<typename T>inline void rd(T&x)
{
    char c;bool f=0;
    while((c=getchar())<'0'||c>'9')if(c=='-')f=1;
    x=c^48;
    while((c=getchar())>='0'&&c<='9')x=x*10+(c^48);
    if(f)x=-x; 
}


const int maxn=105; 
int n,m,k,f[maxn][maxn],hd[maxn];
struct node{
    int to,nt,val;
}e[10005];

inline void add(int x,int y,int z)
{
    e[++k].to=y;e[k].nt=hd[x];hd[x]=k;e[k].val=z;
    e[++k].to=x;e[k].nt=hd[y];hd[y]=k;e[k].val=z;
}

inline void DFS ( int X, int FA, int the Add) 
{ 
    int SON1 = 0 , son2 = 0 ; // left son 
    for ( int I = HD [X]; I; I = E [I] .nt) 
    { 
        int = V E [I] .to;
         IF (FA == V) Continue ;
         IF (SON1!) SON1 = V;
         the else son2 = V; 
        DFS (V, X, E [I] .val);     
    } 
    
    IF (X ! = 1 ) // root nodes in the tree itself accumulated 
    {    
        inc(i,1,m)
        inc(j,0,i-1)
        f[x][i]=max(f[x][i],f[son1][j]+f[son2][i-1-j]+add);
    }
    else //根节点累计儿子苹果数 
    {
        inc(j,0,m)
        f[x][m]=max(f[x][m],f[son1][j]+f[son2][m-j]);
    }
    
}


int main()
{
    freopen("in.txt","r",stdin);
    int x,y,z;
    rd(n),rd(m);
    inc(i,2,n)
    {
        rd(x);rd(y);rd(z);
        add(x,y,z);
    }
    
    dfs(1,0,0);
        
    printf("%d",f[1][m]);
    re 0;
}

 

 

Guess you like

Origin www.cnblogs.com/lsyyy/p/11432947.html