大臣的旅费

该文章介绍了使用Java编程解决图论问题,包括添加边、深度优先搜索(DFS)寻找最远点、广度优先搜索(BFS)确定直径,并利用这些信息计算等差数列的前n项和。
摘要由CSDN通过智能技术生成
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);
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值