牛客練習賽27 水圖(思維+暴搜)
阿新 • • 發佈:2018-10-31
畫幾個圖就可以發現,經過每個點最少一次的最短路徑即使,總邊權*2-從x點出發走的一個最長的路徑,可以想象成這個最長的路徑對應的分支是最後走的,走到了該分支的葉子節點,就滿足要求了,就不必回到x點了,
#include<bits/stdc++.h> using namespace std; #define ll long long const int maxn=50000+10; struct edge { int v,w,nxt; edge(int vv=0,int ww=0,int nxtt=0) { v=vv; w=ww; nxt=nxtt; } }e[2*maxn]; int head[maxn]; ll maxx=-1; void dfs(int now,int fa,ll dis) { for(int i=head[now];i!=-1;i=e[i].nxt) { int v=e[i].v,w=e[i].w; if(v==fa) continue; dfs(v,now,dis+w); } maxx=max(dis,maxx); } int main() { ll ans=0; int n,x,cnt=0; scanf("%d %d",&n,&x); memset(head,-1,sizeof(head)); for(int i=1;i<n;i++) { int u,v,w; scanf("%d %d %d",&u,&v,&w); e[cnt]=edge(v,w,head[u]); head[u]=cnt++; e[cnt]=edge(u,w,head[v]); head[v]=cnt++; ans+=w; } ans*=2; dfs(x,-1,0); printf("%lld\n",ans-maxx); return 0; }