AcWing 849. JAVA _ Dijkstra求最短路 I
原题链接
简单
作者:
acw_weian
,
2020-05-02 12:04:09
,
所有人可见
,
阅读 1278
import java.io.*;
import java.util.*;
/*
* 算法: 贪心思想
* 1. 初始化距离为无穷大, 临接矩阵也初始化为无穷大
* 2. 找到距离最小的点,从该点出发更新到其他点的距离
* 重复1. 2
* 时间复杂度O(n ^ 2)
* 注意, 开一个st数组, 使用过的最小的出发点不再使用
* dijkstra算法的正确性依赖于图中无负权边,与有没有环无关。
*
*
* 堆优化版dijkstra,堆优化就是利用小根堆找到距离最小的点
*
*/
class Main{
static int N = 510, INF = 0x3f3f3f3f, n, m;
static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
static int[][] a = new int[N][N];
static int[] dist = new int[N];
static boolean[] st = new boolean[N];
public static void main(String[] args) throws Exception{
String[] ss = read.readLine().split(" ");
n = Integer.valueOf(ss[0]); m = Integer.valueOf(ss[1]);
for(int i = 1; i <= n; i++){
Arrays.fill(a[i], INF);
a[i][i] = 0;
}
while (m-- > 0){
ss = read.readLine().split(" ");
int l = Integer.valueOf(ss[0]), r = Integer.valueOf(ss[1]), c = Integer.valueOf(ss[2]);
a[l][r] = Math.min(a[l][r], c);
}
Arrays.fill(dist, INF);
int dijk = dijkstra();
if(dijk == INF) log.write("-1");
else log.write(dijk + " ");
log.flush();
}
public static int dijkstra(){
dist[1] = 0;
for(int i = 1; i <= n; i++){
int minNode = -1;
for(int j = 1; j <= n; j++){
if(!st[j] && (minNode == -1 || dist[minNode] > dist[j])){
minNode = j;
}
}
st[minNode] = true;
for(int j = 1; j <= n; j++){
dist[j] = Math.min(dist[j], dist[minNode] + a[minNode][j]);
}
}
return dist[n];
}
}
0x3f3f3f3f 是个人习惯吗?更大一点点,或者小一点点也可以吧?
足够大就行了,又不能太大否则会溢出 int的范围,
为啥把0x3f3f3f3f替换成Integer.MAX_VALUE就不行呢?
dis[j] = Math.min(dis[j], dis[t] + g[t][j]); dis[t] + g[t][j]这个会溢出