namespace BFZ{
int k=1,ssz,rt,tot;
int h[N],dep[N],sz[N],vis[N];
vector<pair<int,int> > G[N];
struct AB{
int a,b,c,n;
}d[N*2];
void cun(int x,int y,int z){
d[++k]={x,y,z,h[x]},h[x]=k;
}
void rebuild(int x,int fa){
int tmp=0,lst=0;
for(auto p:G[x]){
int y=p.first,z=p.second;
if(y==fa) continue;
tmp++;
if(tmp==1) cun(x,y,z),cun(y,x,z),lst=x;
else if(tmp==(int)G[x].size()-(x!=1)) cun(lst,y,z),cun(y,lst,z);
else tot++,cun(lst,tot,0),cun(tot,lst,0),lst=tot,cun(tot,y,z),cun(y,tot,z);
}
for(auto p:G[x]){
if(p.first==fa) continue;
rebuild(p.first,x);
}
}
void dfs(int x,int fa){
for(int i=h[x];i;i=d[i].n){
int y=d[i].b,z=d[i].c;
if(y==fa) continue;
dep[y]=dep[x]+z,dfs(y,x);
}
}
void init(){
tot=n;
for(int i=1,x,y,z;i<n;i++){
scanf("%lld%lld%lld",&x,&y,&z);
G[x].push_back({y,z}),G[y].push_back({x,z});
}
rebuild(1,0);
dfs(1,0);
}
void gt_rt(int x,int fa,int siz){
sz[x]=1;
for(int i=h[x];i;i=d[i].n){
int y=d[i].b;
if(y==fa||vis[i>>1]) continue;
gt_rt(y,x,siz),sz[x]+=sz[y];
int mx_sz=max(siz-sz[y],sz[y]);
if(mx_sz<ssz) ssz=mx_sz,rt=i;
}
}
void dfs2(int x,int fa,int s,int op){
if(x<=n) val[x]=s+dep[x],col[x]=op,q[++top]=x;
for(int i=h[x];i;i=d[i].n){
int y=d[i].b;
if(y==fa||vis[i>>1]) continue;
dfs2(y,x,s+d[i].c,op);
}
}
void solve(int x,int siz){
ssz=1e9,gt_rt(x,0,siz);
if(ssz==1e9) return ;
int i=rt;
vis[i>>1]=1,top=0;
dfs2(d[i].a,0,0,0);
dfs2(d[i].b,0,0,1);
ans=max(ans,d[i].c+XS::work());
int sum=sz[d[i].b];
solve(d[i].a,siz-sum),solve(d[i].b,sum);
}
}
标签:sz,int,siz,分治,tot,lst,cun
From: https://www.cnblogs.com/hubingshan/p/17929480.html