某省自從實行了很多年的暢通工程計劃後,終於修建了很多路。不過路多了也不好,每次要從一個城鎮到另一個城鎮時,都有許多種道路方案可以選擇,而某些方案要比另一些方案行走的距離要短很多。這讓行人很困擾。
現在,已知起點和終點,請你計算出要從起點到終點,最短需要行走多少距離。
Input
本題目包含多組數據,請處理到文件結束。
每組數據第一行包含兩個正整數N和M(0<N<200,0<M<1000),分別代表現有城鎮的數目和已修建的道路的數目。城鎮分別以0~N-1編號。
接下來是M行道路信息。每一行有三個整數A,B,X(0<=A,B<N,A!=B,0<X<10000),表示城鎮A和城鎮B之間有一條長度爲X的雙向道路。
再接下一行有兩個整數S,T(0<=S,T<N),分別代表起點和終點。
Output
對於每組數據,請在一行裏輸出最短需要行走的距離。如果不存在從S到T的路線,就輸出-1.
Sample Input
3 3
0 1 1
0 2 3
1 2 1
0 2
3 1
0 1 1
1 2
Sample Output
2
-1
-----------------------------------------------
附加測試數據:
2 1
0 1 2
1 1
5 5
0 1 3
2 1 1
0 2 1
1 4 20
2 4 60
0 4
4 4
1 2 1
2 3 1
3 2 1
2 1 1
1 3
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author YouYuan
* @eMail E-mail:[email protected]
* @Time 創建時間:2015年8月12日 下午4:27:20
* @Explain 說明:起點和終點可能相同,要輸出0,城鎮之間的道路可能不止一條,要取最小的。被坑了一直WA。
*/
public class Hdu1874最短路徑_暢通工程續 {
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static int nextInt() throws IOException { in.nextToken(); return (int) in.nval;}
static int MAXN = 201;
static int maxNum = 0xfffffff;
static int[][] arc = new int[MAXN][MAXN];//鄰接矩陣儲存圖
static int[] sum = new int[MAXN];//走到當前位置的最小代價
static int n, m, Start, End, MIN;
static Queue<Integer> queue = new LinkedList<Integer>();
public static void main(String[] args) throws IOException {
while(in.nextToken() != in.TT_EOF) {
n = (int) in.nval;
m = nextInt();
initialise();
structure();
Start = nextInt();
End = nextInt();
if (Start == End) {
System.out.println(0);
continue;
}
bfs();
}
}
/**
* 使用廣搜搜索最短路徑
*/
private static void bfs() {
queue.add(Start);
while(!queue.isEmpty()) {
int a = queue.poll();
if (a == End) {
if (sum[a] < MIN) {//判斷是否是較短的路徑
MIN = sum[a];//記錄當前最短路徑,直到所有路徑搜索完畢
}
}
for (int i = 0; i < n; i++) {
if (arc[a][i] != maxNum) {
int s = (sum[a] == maxNum ? 0 : sum[a]) + arc[a][i];//計算到當前頂點的路徑長度
if (s < sum[i]) {//是否小於原路徑長度
sum[i] = s;//更新路徑長度
} else {
continue;
}
queue.add(i);
}
}
}
System.out.println(MIN == maxNum ? -1 : MIN);
}
/**
* 構圖
* @throws IOException
*/
private static void structure() throws IOException {
for (int i = 0; i < m; i++) {
int a = nextInt();
int b = nextInt();
int x = nextInt();
if (arc[a][b] > x || arc[b][a] > x) {//可能同樣路徑有不同的距離,取距離短的
arc[a][b] = x;//雙向路,兩個方向都要保存
arc[b][a] = x;
}
}
}
/**
* 初始化
*/
private static void initialise() {
queue.clear();
for (int i = 0; i < n; i++) {
sum[i] = maxNum;
for (int j = 0; j < n; j++) {
arc[i][j] = maxNum;
}
}
MIN = maxNum;
}
}