#2478. 「九省联考 2018」林克卡特树

本文探讨了一种复杂的图论问题解决方法,通过C++实现并详细解释了关键步骤,如节点遍历、边权更新及最优化路径选择等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这题挺考思路的…我这种渣渣就是做不来.
大佬blog
想了半天,然后看题解了半天…思路还是看大佬的吧.
c++代码如下:

#include<bits/stdc++.h>
#define rep(i,x,y) for(register int i = x ; i <= y; ++ i)
#define repd(i,x,y) for(register int i = x ; i >= y; -- i)
using namespace std;
typedef long long ll;
template<typename T>inline void read(T&x)
{
    x = 0;char c;int sign = 1;
    do { c = getchar(); if(c == '-') sign = -1; }while(!isdigit(c));
    do { x = x * 10 + c - '0'; c = getchar(); }while(isdigit(c));
    x *= sign;
}

const ll inf = 1e12;const int N = 3e5+50;
int n,k;ll K;
int head[N],to[N << 1],nxt[N << 1],w[N << 1],tot;

inline void add(int x,int y,int val)
{
    w[tot] = val;
    to[tot] = y;
    nxt[tot] = head[x];
    head[x] = tot++;
}

#define PI pair<ll,int>
#define mk make_pair
PI f[N][3],t[3];

PI operator + (PI a,PI b) { return mk(a.first + b.first,a.second + b.second); }
PI max(PI a,PI b)
{
    if(a.first > b.first) return a;
    else if(a.first == b.first && a.second < b.second) return a;
    return b;
}

inline void chkmax(PI&a,PI b,int w,int op) { b.first += w - K * op;b.second += op; a = max(a,b); }

inline void update(int x,int y,int w)
{
    t[0] = f[x][0]; t[1] = f[x][1]; t[2] = f[x][2];
    chkmax(f[x][2],t[1] + f[y][1],w,-1);
    chkmax(f[x][2],t[1] + f[y][0],w,0);
    chkmax(f[x][2],t[2] + f[y][2],0,0);

    chkmax(f[x][1],t[0] + f[y][0],w,1);
    chkmax(f[x][1],t[0] + f[y][1],w,0);
    chkmax(f[x][1],t[1] + f[y][2],0,0);

    chkmax(f[x][0],t[0] + f[y][2],0,0);
}

void dfs(int x,int fa)
{
    f[x][0] = mk(0,0);
    f[x][1] = mk(-inf,0);
    f[x][2] = mk(-inf,0);

    for(register int i = head[x];~i;i = nxt[i])
        if(to[i] != fa){
            dfs(to[i],x);
            update(x,to[i],w[i]);
    }

    f[x][2] = max(f[x][2],f[x][1]);
    f[x][2] = max(f[x][2],f[x][0]);
    f[x][2] = max(f[x][2],mk(f[x][0].first-K,f[x][0].second+1));
}

inline bool check(ll x)
{
    K = x;
    dfs(1,1);
    return f[1][2].second <= k;
}

int main()
{
    memset(head,-1,sizeof head);
    read(n); read(k);++k;
    rep(i,2,n)
    {
        int u,v,w;
        read(u); read(v); read(w);
        add(u,v,w); add(v,u,w);
    }

    ll l = -inf,r = inf,mid,ans=0;
    while(l <= r)
    {
        if(check(mid = l + r>> 1)) ans = f[1][2].first + k * K,r = mid - 1;
        else l = mid + 1;
    }

    cout << ans << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值