问题描述
很久以前,T王国空前繁荣。为了更好地管理国家,王国修建了大量的快速路,用于连接首都和王国内的各大城市。为节省经费,T国的大臣们经过思考,制定了一套优秀的修建方案,使得任何一个大城市都能从首都直接或者通过其他大城市间接到达。同时,如果不重复经过大城市,从首都到达每个大城市的方案都是唯一的。J是T国重要大臣,他巡查于各大城市之间,体察民情。所以,从一个城市马不停蹄地到另一个城市成了J最常做的事情。他有一个钱袋,用于存放往来城市间的路费。聪明的J发现,如果不在某个城市停下来修整,在连续行进过程中,他所花的路费与他已走过的距离有关,在走第x千米到第x+1千米这一千米中(x是整数),他花费的路费是x+10这么多。也就是说走1千米花费11,走2千米要花费23。J大臣想知道:他从某一个城市出发,中间不休息,到达另一个城市,所有可能花费的路费中最多是多少呢?
输入格式
输入的第一行包含一个整数n,表示包括首都在内的T王国的城市数。城市从1开始依次编号,1号城市为首都。接下来n-1行,描述T国的高速路(T国的高速路一定是n-1条)。每行三个整数Pi, Qi, Di,表示城市Pi和城市Qi之间有一条高速路,长度为Di千米。
输出格式
输出一个整数,表示大臣J最多花费的路费是多少。
思路
先从1出发,找到距离1最远的点id,然后再从id出发,求最长距离即可。
import java.util.*;
class Edge {
int nxt, to, val;
}
class node {
int dis, id;
node(){}
node(int dis, int id){
this.dis = dis;
this.id = id;
}
}
public class Main {
static Comparator<node> cmp = new Comparator<node>() {
public int compare(node x, node y) {
return y.dis - x.dis; // 由大到小
}
};
static Scanner sc = new Scanner(System.in);
static int n, cnt = 0;
static int N = 100005;
static int inf = Integer.MAX_VALUE;
static int dis[] = new int[N];
static boolean vis[] = new boolean[N];
static int head[] = new int[2 * N];
static Edge edge[] = new Edge[2 * N];
public static void main(String[] args) {
for(int i = 0; i < 2 * N; i++)
head[i] = -1;
n = sc.nextInt();
int a, b, val;
for(int i = 1; i < n; i++) {
a = sc.nextInt();
b = sc.nextInt();
val = sc.nextInt();
add(a, b, val);
add(b, a, val);
}
dijkstra(1);
int tmp = -inf, id = 1;
for(int i = 1; i <= n; i++) {
if(dis[i] > tmp) {
tmp = dis[i];
id = i;
}
}
dijkstra(id);
for(int i = 1; i <= n; i++) {
if(dis[i] > tmp) tmp = dis[i];
}
int sum = 0;
for(int i = 1; i <= tmp; i++) {
sum += 10;
sum += i;
}
System.out.println(sum);
}
static void add(int a, int b, int val) {
edge[cnt] = new Edge();
edge[cnt].to = b;
edge[cnt].val = val;
edge[cnt].nxt = head[a];
head[a] = cnt++;
}
static void dijkstra(int st) {
PriorityQueue<node> queue = new PriorityQueue<node>(cmp);
node tmp = new node();
queue.add(new node(0, st));
for(int i = 1; i <= n; i++) {
dis[i] = -inf;
vis[i] = false;
}
dis[st] = 0;
int x;
while(queue.isEmpty() == false) {
tmp = queue.peek();
queue.poll();
x = tmp.id;
if(vis[x] == true) continue;
vis[x] = true;
for(int i = head[x]; i != -1; i = edge[i].nxt) {
int j = edge[i].to;
if(vis[j] == false && dis[j] < dis[x] + edge[i].val) {
dis[j] = dis[x] + edge[i].val;
queue.add(new node(dis[j], j));
}
}
}
}
}