大臣的旅費--Java實現

問題描述

很久以前,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出發,求最長距離即可。主要是剛開始學java,記錄一下java實現最短路。

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));
				}
			}
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章