链接:https://ac.nowcoder.com/acm/contest/547/E
来源:牛客网
旅行商来到了一个新的国家,这个国家有N个城市,他们直接由N-1条道路相连接,每条道路的长度不尽相同
旅行商现在在1号城市,若他要每一个城市都游览一遍,他需要行走的最短路程是多少?
思路:
1.由于图有n个点 n-1边, 所以一定不存在环。
2.由于分支的存在, 必定要走回头路。不妨假设我们来回走了所有分支的边,最后你会发现其实从1到任意一个分支节点都是可以省略的一步路,那么最优的一定是1到所有的节点路最长的不走。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 100005;
int cnt;
int head[MAXN];
int Max;
struct node{
int from, to, w;
}G[MAXN];
void add(int u, int v, int w)
{
G[cnt].to=v;
G[cnt].w=w;
G[cnt].from=head[u];
head[u]=cnt++;
}
void init()
{
memset(head, -1, sizeof(head));
cnt=0;
Max=-1;
}
void dfs(int cur, int fa, int sum)
{
Max=max(Max, sum);
for(int i=head[cur]; ~i; i=G[i].from)
{
if(fa==G[i].to)
continue;
dfs(G[i].to, cur, sum+G[i].w);
}
return ;
}
int main() {
int n;
scanf("%d", &n);
int x, y, z;
init();
int sum=0;
for(int i=1;i<=n-1;++i)
{
scanf("%d %d %d", &x, &y, &z);
add(x,y,z);
add(y,x,z);
sum+=z;
}
dfs(1, -1, 0);
printf("%d\n", sum*2-Max);
return 0;
}