ural 1018. A Binary Apple Tree

ural 1018. A Binary Apple Tree

#include < iostream >
using   namespace  std;

int  N,k;
int  ch1[ 110 ],ch2[ 110 ],val[ 110 ];
int  f[ 110 ][ 110 ];
int  vis[ 110 ];
inline 
int  max( int  x, int  y){
    
return  x > y ? x:y;
}
void  treedp( int  x){
    
int  root,c1 = 0 ,c2;
    vis[x]
= 1 ;
    
for ( int  i = 1 ;i < N; ++ i)
        
if (ch1[i] == x || ch2[i] == x){
            root
= ch1[i] + ch2[i] - x;
            
if (vis[root])
                f[x][
1 ] = val[i];
            
else {
                
if ( ! c1) c1 = root;  else  c2 = root;
                treedp(root);
            }
        }
    
if (c1)
    
for ( int  i = 1 ;i <= k; ++ i)
        
for ( int  j = 0 ;j < i; ++ j)
            f[x][i]
= max(f[x][i],f[x][ 1 ] + f[c1][j] + f[c2][i - 1 - j]);
}
int  main()
{
    cin
>> N >> k;
    k
++ ;
    
for ( int  i = 1 ;i < N; ++ i)
        cin
>> ch1[i] >> ch2[i] >> val[i];
    memset(f,
0 , sizeof (f));
    memset(vis,
0 , sizeof (vis));
    treedp(
1 );
    cout
<< f[ 1 ][k] << endl;
    
return   0 ;
}



你可能感兴趣的:(ural 1018. A Binary Apple Tree)