标签:iostream max names class 二次 clu 扫描 const string
#include<queue>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
using namespace std;
typedef long long ll;
const int maxm=2e5+7;
int t,n;
int last[maxm],other[maxm+maxm],len[maxm<<1],pre[maxm<<1],l;
int dp[maxm];//以i为根的子树中,把i作为源点的最大流量
int f[maxm];//以i为源点的最大流量 
int du[maxm];
void add(int x,int y,int z)
{
 l++;
 pre[l]=last[x];
 last[x]=l;
 other[l]=y;
 len[l]=z;  
}
void dfs(int x,int fa)
{
  for(int p=last[x];p;p=pre[p])
  {
    int v=other[p];
    if(v==fa) continue;
    dfs(v,x);
    if(du[v]!=1)dp[x]+=min(dp[v],len[p]);
    if(du[v]==1) dp[x]+=len[p]; 
  }
}
void dfs1(int x,int fa)
{
 for(int p=last[x];p;p=pre[p])
 {
  int v=other[p];
  if(v==fa) continue;
  if(du[x]==1)
  f[v]=dp[v]+len[p];
  else f[v]=dp[v]+min(f[x]-min(dp[v],len[p]),len[p]);//f[x]-min(dp[v],len[p])为x流向其他部分的流量 
  dfs1(v,x);
 }
}
int main()
{
 scanf("%d",&t);
 while(t--)
 {
  memset(last,0,sizeof(last));
  l=0;
  memset(du,0,sizeof(du));
  memset(dp,0,sizeof(dp));
  scanf("%d",&n);
  for(int i=1;i<=n-1;i++)
  {
   int x,y,z;
   scanf("%d%d%d",&x,&y,&z);
   add(x,y,z);
   add(y,x,z);
   du[x]++;
   du[y]++;
  }
  dfs(1,0);//先以1为根
  f[1]=dp[1];
  dfs1(1,0);
  int ans=0;
  for(int i=1;i<=n;i++)
  ans=max(ans,f[i]);
  printf("%d\n",ans); 
 }
 return 0;  
}标签:iostream max names class 二次 clu 扫描 const string
原文地址:https://www.cnblogs.com/lihan123/p/11765406.html