[八省联考2018]林克卡特树lct

#include<bits/stdc++.h>
#define RG register
#define IL inline
#define _ 500005
#define INF 1e18
#define ll long long
using namespace std;

IL ll gi(){
    RG ll data = 0 , m = 1; RG char ch = 0;
    while(ch != '-' && (ch<'0' || ch > '9')) ch = getchar();
    if(ch == '-'){m = 0; ch = getchar();}
    while(ch>='0' && ch<='9'){data = (data<<1) + (data<<3) + ch - '0' ;  ch = getchar();}
    return (m) ? data : -data ; 
}

struct DP{
    ll v , cnt ; 
    IL DP(){cnt = v = 0 ; }
    IL DP(RG ll a , RG ll b){v = a ; cnt = b ; }
    IL void mem(){cnt = v = 0 ; }
    DP operator + (RG DP &B){return DP(v + B.v , cnt + B.cnt) ; }
    DP operator + (RG ll &B){return DP(v + B , cnt) ; }
    DP operator * (RG DP &B){return DP(v + B.v , cnt + B.cnt - 1) ; }
}f[_][3],Ans[_],tmp; 
IL DP Max(RG DP A , RG DP B){
    if(A.v ^ B.v) return (A.v < B.v) ? B : A ; 
    else return (A.cnt < B.cnt) ? B : A ;  
}
ll n,K,L,R,C,Ret,head[_]; struct Edge{ll to,next,w;}t[_<<2] ; ll oo ;  

IL void add(RG ll u,RG ll v,RG ll w){
    t[++oo] = (Edge){v , head[u] , w} ; head[u] = oo ; 
    t[++oo] = (Edge){u , head[v] , w} ; head[v] = oo ; 
}

void dfs(RG ll u,RG ll From){
    f[u][0] = (DP){0 , 0} ; Ans[u] = (DP){-INF , 0} ; 
    f[u][1] = (DP){-C , 1} ; f[u][2] = (DP){-INF , 0} ;  
    for(RG ll i = head[u] ; i ; i = t[i].next){
        RG ll v = t[i].to ; if(v == From) continue ; 
        dfs(v , u) ; 
        f[u][2] = Max(f[u][2] , f[u][2] + Ans[v]) ; 
        f[u][2] = Max(f[u][2] , (f[u][1] * f[v][1]) + t[i].w + C) ;
        tmp = f[u][0] + f[v][0]; C = -C ; tmp = tmp + t[i].w + C; C = -C ; tmp.cnt ++ ; 
        f[u][1] = Max(f[u][1] , f[u][1] + Ans[v]) ; 
        f[u][1] = Max(f[u][1] , Max(f[u][0] + f[v][1] + t[i].w , tmp)) ; 
        f[u][0] = Max(f[u][0] , f[u][0] + Ans[v]) ;
    } 
    Ans[u] = Max(Max(f[u][0] , f[u][1]) , f[u][2]) ; return ; 
}

int main(){
    n = gi() ; K = gi() ; 
    for(RG ll i = 1,u,v,w; i < n; i ++)
        u = gi() , v = gi() , w = gi() , add(u , v , w) , R = R + abs(w);
    ++ K ;  L = -R ; 
    while(L <= R){
        C = (L + R) >> 1 ;		 
        dfs(1 , 0) ; 
        if(Ans[1].cnt <= K) Ret = C , R = C - 1 ; 
        else L = C + 1; 		
    }
    C = Ret ; dfs(1 , 0) ;  
    printf("%lld\n" , Ans[1].v + Ret * Ans[1].cnt) ; return 0 ;	    
}
posted @ 2018-05-17 15:37  Guess2  阅读(287)  评论(0编辑  收藏  举报