当前位置:网站首页>Change the root

Change the root

2022-06-10 20:03:00 2020100XWH

Sign in — major IT Written interview preparation platform _ Cattle from

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

  New array record prevention dfs The disorderly , Define traffic, especially leaf nodes , When the leaf node is replaced, it is handled separately

原网站

版权声明
本文为[2020100XWH]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101740233518.html