大臣的旅费
方法一
- 如果不重复经过大城市,从首都到达每个大城市的方案都是唯一的。
- 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;
}
}
}










