luogu P1099 树网的核

树的直径的结论:

1.所有直径相较于一点,且为边的中点。

2.以直径上一点为根的子树,深度不超过这一点到较近的端点的距离。

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 500005;
const int maxm = 1000005;
int he[maxn],ver[maxm],ne[maxm],tot = 1;
LL cost[maxm];
void add( int x,int y,LL z ){
    ver[++tot] = y;
    ne[tot] = he[x];
    he[x] = tot;
    cost[tot] = z;
}
int s,t,fa[maxn];
LL d[maxn],mx;
void dfs(int x,int f){
    for( int cure= he[x];cure;cure=  ne[cure] ){
        int y = ver[cure];
        if(y==f) continue;
        d[y] = d[x]+cost[cure];
        fa[y] = (cure^1);
        dfs(y,x);
        if(d[y] > mx){
            mx = d[y];
            s = y;
        }
    }
}
int vis[maxn];
LL sum[maxn];
void dfs2( int x,int f ){
    for( int cure = he[x];cure;cure= ne[cure] ){
        int y = ver[cure];
        if( y == f || vis[y] ) continue;
        d[y] = d[x] + cost[cure];
        mx = max(mx,d[y]);
        dfs2(y,x);
    }
}
int main(){
    int n,x,y;
    LL z,len;
    scanf("%d%lld",&n,&len);
    for( int i = 1;i < n;i++ ){
        scanf("%d%d%lld",&x,&y,&z);
        add(x,y,z);add(y,x,z);
    }
    d[1] = 0;
    mx= 0 ;
    dfs(1,0);
    t =s;
    mx = 0;
    d[t] = 0;
    dfs(t,0);
    int num = 1;
    fa[t] = 0;
    for( int i = s;i;i = ver[fa[i]] ) {
        vis[i] = 1;
        d[i] = 0;
        if(fa[i]){
            num++;
            sum[num] = sum[num-1]+cost[fa[i]];
        }
    }
    mx = 0;
    for( int i = s;i;i = ver[fa[i]] ){
        dfs2(i,0);
    }
    int r = 1;
    LL mn = 0x3f3f3f3f3f3f3f3f;
    for( int l = 1;l <= num;l++ ){
        while(  r < l ||(r < num && sum[r+1] - sum[l] <=len)  )r++;
         mn= min(mn,max( sum[l],sum[num]-sum[r] ));
    }
    mx = max(mx,mn);
    printf("%lld\n",mx);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值