换根呀呀啊呀

登录—专业IT笔试面试备考平台_牛客网

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+5000;
struct edge{
    ll to,next,w;
}e[N*2];
ll head[N],tot,flow[N],deg[N],sum,ans[N];
void addedge(ll u,ll v,ll z)
{
    e[tot].to=v;
    e[tot].w=z;
    e[tot].next=head[u];
    head[u]=tot++;
}
void dfs1(ll x,ll fa)
{
    ll to;
    for(int i=head[x];i!=-1;i=e[i].next)
    {
        to=e[i].to;
        if(to==fa)
            continue;
        dfs1(to,x);
        if(deg[to]==1)
            flow[x]+=e[i].w;
        else flow[x]+=min(e[i].w,flow[to]);
    }
}
bool vis[N];
void dfs2(ll x)
{
    ll to;
    vis[x]=1;
    for(ll i=head[x];i!=-1;i=e[i].next)
    {
        to=e[i].to;
        if(vis[to])
            continue;
        if(deg[x]>1)
        {
            //flow[to]+=flow[x]-min(e[i].w,flow[to]);
            ans[to]=flow[to]+min(ans[x]-min(flow[x],e[i].w),e[i].w);
        }
        else {
            ans[to]=flow[to]+e[i].w;
        }
        dfs2(to);
    }
}
int main ()
{
    int t;
    cin>>t;
    ll x,y,z;
    ll n;
    while(t--)
    {
        tot=0;
        memset(head,-1,sizeof(head));
        memset(flow,0,sizeof(flow));
        memset(deg,0,sizeof(deg));
        cin>>n;
        for(int i=1;i<n;++i)
        {
            vis[i]=0;
            cin>>x>>y>>z;
            addedge(x,y,z);
            addedge(y,x,z);
            deg[x]++;
            deg[y]++;
        }
        dfs1(1,-1);
//         for(int i=1;i<=n;++i)
//             cout<<flow[i]<<" ";
        //cout<<sum<<"\n";
        ans[1]=flow[1];
        dfs2(1);
        sum=ans[1];
        for(int i=2;i<=n;++i)
        {
            sum=max(sum,ans[i]);
        }
        cout<<sum<<endl;
    }
    return 0;
}

 新开数组记录防止dfs乱,定义流量尤其叶子结点,换出叶子结点时单独处理

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值