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
| #include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<cmath> #include<queue> #include<cctype> #include<bitset> #include<vector> #include<map> #include<set> using namespace std; const int N=1e5+5;
struct edge{ int to,nxt,val; }e[N]; int head[N],cnt; inline void add(int u,int v,int w){ e[++cnt].val=w; e[cnt].to=v; e[cnt].nxt=head[u]; head[u]=cnt; } template <typename T> void read(T &x){ x=0; char c=getchar(); int f=0; for(; !isdigit(c); c=getchar()) f |= c=='-'; for(; isdigit(c); c=getchar()) x = (x<<3)+(x<<1)+(c^48); if(f) x = -x; } template <typename T> void write(T x){ if(x<0) putchar('-'), x = -x; static short st[30],tp; do st[++tp] = x%10, x/=10; while(x); while(tp) putchar(st[tp--] | 48); putchar('\n'); }
int p1[N]; int n,m; int up[N]; pair<int,int> down[N];
inline int dfs_down(int u,int f){ for(int i=head[u];i;i=e[i].nxt){ int v=e[i].to,w=e[i].val; if(v==f) continue; int d=dfs_down(v,u)+w; if(down[u].first<d){ p1[u]=v; down[u].second=down[u].first; down[u].first=d; } else if(down[u].second<d) down[u].second=d; } return down[u].first; }
inline void dfs_up(int u,int f){ for(int i=head[u];i;i=e[i].nxt){ int v=e[i].to,w=e[i].val; if(v==f) continue;
if(p1[u]==v) up[v]=max(down[u].second,up[u])+w; else up[v]=max(up[u],down[u].first)+w; dfs_up(v,u); } } int main(){ read(n); for(int i=1,u,v,w;i<n;i++){ read(u),read(v),read(w); add(u,v,w); add(v,u,w); } dfs_down(1,-1); dfs_up(1,-1); int ans=2e9; for(int i=1;i<=n;i++) ans=min(ans,max(down[i].first,up[i])); write(ans); return 0; }
|