java-A-10大臣的旅费

大臣的旅费

方法一

  • 如果不重复经过大城市,从首都到达每个大城市的方案都是唯一的。
  • n -1 行,描述 T 国的高速路( T 国的高速路一定是 nn -1 条).
  • 从这两条信息可以看出这是一棵树,但是没说是几叉树,所以我们最好用图来表示。

在这里插入图片描述

在这里插入图片描述

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
	
	private static int n;
	private static List<Node>[] g; // 图的邻接表
	private static int max = -1;
	private static int pnt = -1;
	static int dis2money(int dis) {
		return 11*dis+dis*(dis-1)/2;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		g = new List[n+1];
		for (int i = 1; i <= n; i++) {
			g[i] = new ArrayList<Node>();
		}
		for (int i = 0; i < n-1; i++) {
			int a = sc.nextInt();
			int b = sc.nextInt();
			int c = sc.nextInt();
			g[a].add(new Node(b, c));
			g[b].add(new Node(a, c));
		}
		
		dfs(1,1,0);
//		System.out.println(pnt); // 打印找到 的端点
		dfs(pnt,pnt,0);
		System.out.println(dis2money(max));
	}
	/**
	 * 
	 * @param from 来自上一个点 , from 是编号
	 * @param num 当前的点
	 * @param dis 历史上积累的距离
	 */
	private static void dfs(int from, int num, int dis) {
		boolean isLeaf = true;
		List<Node> neighbors = g[num];
		for (int i = 0; i < neighbors.size(); i++) {
			Node neighbor = neighbors.get(i);
			if(neighbor.num == from) continue;
			isLeaf = false;
			dfs(num, neighbor.num, dis+neighbor.dis);
		}
		if (isLeaf&&dis > max) { // 是叶子结点
			max = dis;
			pnt = num;
		}
	}

	static class Node{
		int num;
		int dis;
		public Node(int num, int dis) {
			super();
			this.num = num;
			this.dis = dis;
		}
		
	}
}

) {
super();
this.num = num;
this.dis = dis;
}

}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值