using namespace std; struct node{ int to,w; node(int to,int w):to(to),w(w){} }; vector<node>e[maxn]; int n; int vis[maxn],deep[maxn],f[maxn],anc[maxn][25]; LL dis[maxn],temp[maxn]; void dfs(int x,int fa){ anc[x][0]=f[x]; for(int i=1;i<=20;i++) anc[x][i]=anc[anc[x][i-1]][i-1]; for(int i=0;i<e[x].size();i++){ int next=e[x][i].to; if(next!=fa){ f[next]=x; deep[next]=deep[x]+1; dfs(next,x); } } } int lca(int x,int y){ if(deep[x]<deep[y]) swap(x,y); for(int i=20;i>=0;i--) if(deep[anc[x][i]]>=deep[y]) x=anc[x][i]; if(x==y) return x; for(int i=20;i>=0;i--) if(anc[x][i]!=anc[y][i]) x=anc[x][i],y=anc[y][i]; return f[x]; } void dfs2(int id){ for(int i=0;i<e[id].size();i++){ int next=e[id][i].to,ww=e[id][i].w; if(vis[next]) continue; dis[next]=(LL)dis[id]+ww; vis[next]=1; dfs2(next); } } int main(){ // freopen("input.txt","r",stdin); ios::sync_with_stdio(false); cin.tie(0); while(cin>>n){ for(int i=0;i<=n;i++) e[i].clear(); for(int i=1;i<n;i++){ int u,v,w; cin>>u>>v>>w; e[u].push_back(node(v,w)); e[v].push_back(node(u,w)); } memset(f,0,sizeof(f)); memset(anc,0,sizeof(anc)); memset(deep,0,sizeof(deep)); deep[1]=1; dfs(1,0); memset(dis,0,sizeof(dis)); memset(vis,0,sizeof(vis)); vis[1]=1; dfs2(1); int id1=0,id2=0; LL mx=0; for(int i=1;i<=n;i++){ if(mx<dis[i]){ mx=dis[i]; id1=i; } } memcpy(temp,dis,sizeof(dis)); memset(dis,0,sizeof(dis)); memset(vis,0,sizeof(vis)); vis[id1]=1; dfs2(id1); mx=0; for(int i=1;i<=n;i++){ if(mx<dis[i]){ mx=dis[i]; id2=i; } } LL ans=-mx; for(int i=1;i<=n;i++){ int f1=lca(i,id1); int f2=lca(i,id2); LL d1=temp[i]+temp[id1]-2*temp[f1]; LL d2=temp[i]+temp[id2]-2*temp[f2]; ans+=max(d1,d2); } cout<<ans<<endl; } return 0; }
|