AcWing 849. Dijkstra求最短路 I-java
原题链接
简单
作者:
Susu
,
2020-01-30 10:07:46
,
所有人可见
,
阅读 661
import java.util.*;
public class Main{
static int N = 510;
static int n,m;
static int[][] g = new int[N][N];
static int[] dist = new int[N];
static boolean[] st = new boolean[N];
static int dijkstra(){
for(int i=0;i<N;i++){
dist[i]=0x3f3f3f;
}
dist[1]=0;
for(int i=0;i<n;i++){
int t = -1;
for(int j=1;j<=n;j++){
if(!st[j] && (t==-1 || dist[t]>dist[j])){
t = j;
}
}
st[t] = true;
for(int j=1;j<=n;j++){
dist[j] = Math.min(dist[j],dist[t]+g[t][j]);
}
}
if(dist[n]==0x3f3f3f) return -1;
return dist[n];
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
g[i][j]=0x3f3f3f;
}
}
while(m-->0){
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
g[x][y] = Math.min(g[x][y], z);
}
System.out.print(dijkstra());
}
}