码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-05-17 16:01:02      阅读:331      评论:0      收藏:0      [点我收藏+]

标签:data   code   c++   getch   mes   return   ==   its   rom   

#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 ;     
}

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

标签:data   code   c++   getch   mes   return   ==   its   rom   

原文地址:https://www.cnblogs.com/Guess2/p/9051429.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!