输入样例:
3 3
1 2 2
2 3 1
1 3 4
输出样例:
3
算法思路:
dijkstra的朴素版时间复杂度为O(n^2),其中在找没有确定距离的点中的最小值上最耗费时间,找最短距离的过程为O(n),可以将所有点放于堆中,实现O(1)内取出最小值。朴素版主要处理稠密图,堆优化处理稀疏图,其中在更新图中点的距离时,若用邻接矩阵开销太大,需要用邻接表存储,总共要更新m次,每次往堆中放元素的复杂度为O(logm),算法总共的复杂度为O(mlogm),由于m最多为n^2,所以也相当于O(mlogn)。其中n为图中顶点数,m为图中边数。
朴素版dijkstra算法
https://blog.csdn.net/weixin_48898946/article/details/124112903
Java代码:
import java.io.*;
import java.util.*;
public class Main {
static int n, m;
static final int N = 150005;
static int []h = new int[N];
static int []w = new int[N]; // 每个地址对应的权值
static int []e = new int[N];
static int []ne = new int[N];
static int idx = 0; // 模拟地址
static int []dis = new int[N];
static boolean []vis = new boolean[N];
static final int INF = 0x3f3f3f3f;
static class Node implements Comparable<Node>{
int dis; // 结点距源点的距离
int ver; // 结点的编号
public Node(int dis, int ver) {
this.dis = dis;
this.ver = ver;
}
@Override
public int compareTo(Node o) { // 按距离排序
return this.dis - o.dis;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] split = br.readLine().split(" ");
n = Integer.parseInt(split[0]);
m = Integer.parseInt(split[1]);
Arrays.fill(h, -1); // 初始时,头结点都指向空(-1)
for(int i = 0; i < m; i++) {
split = br.readLine().split(" ");
int a = Integer.parseInt(split[0]);
int b = Integer.parseInt(split[1]);
int c = Integer.parseInt(split[2]);
add(a, b, c);
}
System.out.println(dijkstra());
}
public static int dijkstra() {
Arrays.fill(dis, INF); // 1.初始化dis数组
dis[1] = 0;
PriorityQueue<Node> heap = new PriorityQueue<>(); // 模拟小根堆(从小到大排序)
heap.add(new Node(0, 1));
while(!heap.isEmpty()) { // 2.迭代,将所有未被访问的点都找到
Node no = heap.poll(); // 3.在没有确定的点中找到距离源点最近的点t
int d = no.dis, ver = no.ver;
if(vis[ver]) continue; // 过滤已经确定的点
vis[ver] = true;
for(int i = h[ver]; i != -1; i = ne[i]) { //4.更新t的邻接边
int j = e[i];
if(dis[j] > d + w[i]) {
dis[j] = d + w[i];
heap.add(new Node(dis[j], j));
}
}
}
return dis[n] == INF ? -1 : dis[n];
}
public static void add(int a, int b, int c) {
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx++;
}
}