Problem Description
在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt。但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要寻找最短的从商店到赛场的路线,你可以帮助他们吗?
Input
输入包括多组数据。每组数据第一行是两个整数N、M(N<=100,M<=10000),N表示成都的大街上有几个路口,标号为1的路口是商店所在地,标号为N的路口是赛场所在地,M则表示在成都有几条路。N=M=0表示输入结束。接下来M行,每行包括3个整数A,B,C(1<=A,B<=N,1<=C<=1000),表示在路口A与路口B之间有一条路,我们的工作人员需要C分钟的时间走过这条路。
输入保证至少存在1条商店到赛场的路线。
输入保证至少存在1条商店到赛场的路线。
Output
对于每组输入,输出一行,表示工作人员从商店走到赛场的最短时间
Sample Input
2 1 1 2 3 3 3 1 2 5 2 3 5 3 1 2 0 0
Sample Output
3 2
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
new Task().solve();
}
}
class Task {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
class Node implements Comparable<Node>{
int v , w ;
Node(int v , int w){
this.v = v ;
this.w = w ;
}
@Override
public int compareTo(Node other) {
return Integer.compare(this.w , other.w) ;
}
}
int spfa(int s , int t , List<Node> adj[]){
int[] dist = new int[t+1] ;
Arrays.fill(dist , Integer.MAX_VALUE) ;
PriorityQueue<Node> q = new PriorityQueue<Node>() ;
q.add(new Node(s, 0)) ;
dist[s] = 0 ;
while(! q.isEmpty()){
Node nd = q.poll() ;
int u = nd.v ;
if(u == t){
return nd.w ;
}
for(Node v : adj[u]){
if(nd.w + v.w < dist[v.v]){
dist[v.v] = nd.w + v.w ;
q.add(new Node(v.v , dist[v.v])) ;
}
}
}
return -1 ;
}
void solve() {
while(true){
int n = in.nextInt() ;
int m = in.nextInt() ;
if(n == 0 && m == 0){
break ;
}
List<Node>[] adj = new List[n+1] ;
for(int i = 1 ; i <= n ; i++){
adj[i] = new ArrayList<Node>() ;
}
while(m-- > 0){
int u = in.nextInt() ;
int v = in.nextInt() ;
int w = in.nextInt() ;
adj[u].add(new Node(v, w)) ;
adj[v].add(new Node(u, w)) ;
}
out.println(spfa(1, n, adj)) ;
}
out.flush();
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = new StringTokenizer("");
}
private void eat(String s) {
tokenizer = new StringTokenizer(s);
}
public String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String s = nextLine();
if (s == null)
return false;
eat(s);
}
return true;
}
public String next() {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
}