旅行商来到了一个新的国家,这个国家有N个城市,他们直接由N-1条道路相连接,每条道路的长度不尽相同
旅行商现在在1号城市,若他要每一个城市都游览一遍,他需要行走的最短路程是多少?
解析
如果用dfs解决的话,需要逆向考虑这个问题,可以想到,肯定有路要走两次,有一条路只走一次即可,那么我们就希望这条只走一次的路可以尽可能地长,所以dfs找到这条最长的路就好了,然后其他的路走两次,这条路只需要走一次,总的路程就是sum*2-ans(ans是这条最长的路)
import java.io.BufferedReader;
import java.io.*;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Main {
static int N=50000*2+10;
static int []head=new int [N];
static int []next =new int [N];
static int []to= new int [N];
static int []dis =new int [N];
static int [] d=new int [N];
static int now=0,ans=0;
static void add(int x ,int y,int z) {
now++;
to[now]=y;
dis[now]=z;
next[now]=head[x];
head[x]=now;
}
static void dfs(int x,int pre,int k) {
//System.out.println(now);
ans=Math.max(ans,k);
for(int i=head[x];i!=0;i=next[i]) {
int y=to[i];
if(y!=pre) {
dfs(y,x,k+dis[i]);
}
}
}
public static void main(String []args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();
int n=Integer.parseInt(str);
n--;
int sum=0;
while(n--!=0) {
str=br.readLine();
String []s =str.split(" ");
int x=Integer.parseInt(s[0]);
int y=Integer.parseInt(s[1]);
int z =Integer.parseInt(s[2]);
add(x,y,z);
add(y,x,z);
sum+=z;
}
dfs(1,-1,0);
System.out.println(sum*2-ans);
}
}