Solution
很容易发现,该题目给出的图是一棵树。首都为 ,可以看作根为 。
题目的要求是每个点都走一遍,求最少路径。假如最终要回到首都,那么结果就是所有边权的和再乘上 ,但是题目说可以不回到首都,这就说明最优情况下我们最后是停在叶子上的,那么少走的路径就是从叶子一直到根的距离,由于要路劲最小,那么贪心一下,选择距离最长的那个叶子作为最后的位置即可。
时间复杂度 。
AC code
#include <bits/stdc++.h>
using namespace std;
#define int long long
int n,x,y,z,ans,maxx;
vector<pair<int,int>> edge[100005];
void dfs(int now,int fa,int sum){
for(auto to:edge[now]) if(to.first!=fa) dfs(to.first,now,sum+to.second);
maxx=max(maxx,sum);
}
signed main(){
cin>>n;
for(int i = 1;i<n;i++) cin>>x>>y>>z,edge[x].push_back({y,z}),edge[y].push_back({x,z}),ans+=z*2;
dfs(1,0,0);
cout<<ans-maxx;
return 0;
}