# bzoj 5341: [Ctsc2018]暴力写挂

## Solution

#include<bits/stdc++.h>
#define vc vector<edge>::iterator
#define pb push_back
using namespace std;
typedef long long ll;
const int N=750000,M=8510000,T=N*2;
int n,V,sz[N],sum,son[N]={N},val[T],ls[T],rs[T],dep[N],fa[T],tt=0;
ll f[N][20],dis[N],fl[M],fr[M],ans=0,D;int lm[M],rm[M],rt[N/2],id[M];
struct edge{
int x,v;
edge(){}
edge(int _x,int _v){x=_x;v=_v;}
}q[N];
vector<edge>G1[N],G2[N/2];
inline void add(int x,int y,int z,vector<edge>*G){
G[x].pb(edge(y,z));G[y].pb(edge(x,z));
}
inline void build(int x,int last){
for(vc it=G1[x].begin();it!=G1[x].end();++it){
if(it->x==last)continue;
dis[it->x]=dis[x]+it->v;build(it->x,x);
}
int l=1,r=0;edge u,v;
for(vc it=G1[x].begin();it!=G1[x].end();++it)if(it->x!=last)q[++r]=*it;
while(l+2<=r){
int o=++V;u=q[l++],v=q[l++];
q[++r]=edge(o,0);
}
vector<edge>().swap(G1[x]);
}
inline void getdis(int x,int last,int d){
for(vc it=G1[x].begin();it!=G1[x].end();++it){
if(it->x==last || it->x==-1)continue;
f[it->x][d]=f[x][d]+it->v;getdis(it->x,x,d);
}
}
inline void getedge(int x,int last,int &ex,int &ey){
sz[x]=1;
for(int i=G1[x].size()-1,u;i>=0;i--){
if((u=G1[x][i].x)==last || u==-1)continue;
getedge(u,x,ex,ey);sz[x]+=sz[u];
if(son[u]<son[ey])ex=x,ey=u;
}
son[x]=abs(sum-2*sz[x]);
}
inline int solve(int x,int S,int d){
if(S==1){dep[x]=d;return x;}
int ex=0,ey=0,o=++V;
getdis(x,x,d);
sum=S;getedge(x,x,ex,ey);
for(vc it=G1[ex].begin();it!=G1[ex].end();++it)
if(it->x==ey){val[o]=it->v;it->x=-1;break;}
for(vc it=G1[ey].begin();it!=G1[ey].end();++it)
if(it->x==ex){it->x=-1;break;}
fa[ls[o]=solve(ex,S-sz[ey],d+1)]=o;
fa[rs[o]=solve(ey,sz[ey],d+1)]=o;
return o;
}
inline int ins(int x){
for(int i=dep[x],u=x,la=x;i>=1;i--){
id[++tt]=fa[x];fl[tt]=fr[tt]=-1ll<<60;
if(ls[fa[x]]==x)fl[tt]=max(fl[tt],dis[u]+f[u][i]),lm[tt]=la;
if(rs[fa[x]]==x)fr[tt]=max(fr[tt],dis[u]+f[u][i]),rm[tt]=la;
la=tt;x=fa[x];
}
return tt;
}
inline int merge(int x,int y){
if(!x||!y)return x+y;
ans=max(ans,(fl[x]+fr[y]+val[id[x]])/2-D);
ans=max(ans,(fl[y]+fr[x]+val[id[x]])/2-D);
fl[x]=max(fl[x],fl[y]);fr[x]=max(fr[x],fr[y]);
lm[x]=merge(lm[x],lm[y]);rm[x]=merge(rm[x],rm[y]);
return x;
}
inline void dfs(int x,int last,ll d){
rt[x]=ins(x);ans=max(ans,dis[x]-d);
for(vc it=G2[x].begin();it!=G2[x].end();++it){
if(it->x==last)continue;
dfs(it->x,x,d+it->v);D=d;
rt[x]=merge(rt[x],rt[it->x]);
}
}
int main(){
freopen("pp.in","r",stdin);
freopen("pp.out","w",stdout);
cin>>n;V=n;
int x,y,z;