大臣的旅费

import java.util.Arrays;
import java.util.Scanner;

public class Main{
    static int n,idx;
    static int N = 100010;
    static int M = 200010;
    static int[] h = new int[N];
    static int[] ne = new int[M];
    static int[] e = new int[M];
    static int[] w = new int[M];
    static int[] dist = new int[M];

    public static void add(int a,int b,int c){
        e[idx] = b;
        w[idx] = c;
        ne[idx] = h[a];
        h[a] = idx++;
    }

    public static void dfs(int u,int father,int distance){
        dist[u] = distance;
        for(int i = h[u];i != -1;i = ne[i]){
            int j = e[i];
            if (j != father){
                dfs(j,u,distance + w[i]);
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();

        Arrays.fill(h,-1);

        for(int i = 1;i <= n - 1;i++){
            int a = sc.nextInt();
            int b = sc.nextInt();
            int c = sc.nextInt();
            add(a,b,c);
            add(b,a,c);
        }
        //随便找个数搜到最远
        dfs(1,-1,0);

        //找到最远那个点
        int max_idx = 1;
        for(int i = 2;i <= n;i++){
            if (dist[max_idx] < dist[i])
                max_idx = i;
        }
        
        //从最远那个点搜回去,就是直径
        dfs(max_idx,-1,0);
        int max = dist[1];
        for(int i = 2;i <= n;i++){
            if (max < dist[i])
                max = dist[i];
        }

        //等差数列前n项和
        System.out.println(10 * max + (long) max * (1 + max) / 2);
    }
}

你可能感兴趣的:(蓝桥杯,深度优先,算法)