1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| #include<bits/stdc++.h> using namespace std; #define int long long inline int read(){int x=0,f=1;char ch=getchar(); while(ch<'0'|| ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){ x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}return x*f;} #define Z(x) (x)*(x) #define pb push_back
#define N 200010
struct node { int w, x; bool operator < (const node &A) const { return w<A.w; } bool operator > (const node &A) const { return w>A.w; } }mx1[N], mx2[N], mx3[N], mx4[N], s1[N], s2[N]; struct Node { int y, z; }; int n, m, i, j, k, T; int u, v, w, ans, sum, d[N]; vector<Node>G[N];
void work(node y, int x) { if(y>mx1[x]) mx4[x]=mx3[x], mx3[x]=mx2[x], mx2[x]=mx1[x], mx1[x]=y; else if(y>mx2[x]) mx4[x]=mx3[x], mx3[x]=mx2[x], mx2[x]=y; else if(y>mx3[x]) mx4[x]=mx3[x], mx3[x]=y; else if(y>mx4[x]) mx4[x]=y; }
void work2(node y, int x) { if(y>s1[x]) s2[x]=s1[x], s1[x]=y; else if(y>s2[x]) s2[x]=y; }
void dfs1(int x, int fa) { for(auto t : G[x]) { int y=t.y, z=t.z; if(y==fa) continue; dfs1(y, x); work({mx1[y].w+z, y}, x); work2({max(s1[y].w, d[y]), x}, x); d[x]=max(d[x], d[y]); } d[x]=max(d[x], mx1[x].w+mx2[x].w); }
void dfs2(int x, int fa) { for(auto t : G[x]) { int y = t.y, z = t.z; if(y == fa) continue; node f; f.x=x; f.w=z; if(mx1[x].x==y) f.w+=mx2[x].w; else f.w+=mx1[x].w;
work(f, y); dfs2(y, x); } ans=max(ans, mx1[x].w+mx2[x].w+mx3[x].w+mx4[x].w);
}
void Choose_Not(int &s, int x, int y) { if(mx1[x].x==y) s+=mx2[x].w+mx3[x].w; else if(mx2[x].x==y) s+=mx1[x].w+mx3[x].w; else s+=mx1[x].w+mx2[x].w; }
void dfs3(int x, int fa, int D) { for(auto t : G[x]) { int y = t.y, z = t.z; if(y == fa) continue; int newd=0; Choose_Not(newd, x, y); newd=max(newd, D); if(s1[x].x==y) newd=max(newd, s1[x].w); else newd=max(newd, s2[x].w);
ans=max(ans, 2*z+d[y]+newd); dfs3(y, x, newd); } }
signed main() {
n=read(); for(i=1; i<n; ++i) { u=read(); v=read(); w=read(); sum+=2*w; G[u].pb({v, w}); G[v].pb({u, w}); } dfs1(1, 0); dfs2(1, 0); dfs3(1, 0, 0);
printf("%lld", sum-ans); return 0; }
|