dijkstra是一种单源最短路径算法,时间复杂度上限为O(n^2)(朴素),在实际应用中较为稳定;加上堆优化之后更是具有O((n+m)log2n)的时间复杂度,在稠密图中有不俗的表现。
题目传送门:P4779 【模板】单源最短路径(标准版) - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
import java.io.*;
import java.util.*;
public class 最短路 {//链式前向星 优先队列 堆优化
static Edge[] e;
static int cnt = 0, n, m, s, MAX = 2147483647;
static int[] head;
static boolean[] vis;
static int[] dist;
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static Comparator<Node> cmp = new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
return o1.d - o2.d;
}
};
static int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
public static void main(String[] args) throws IOException {
n = nextInt();
m = nextInt();
s = nextInt();
e = new Edge[200005];
head = new int[100005];
vis = new boolean[100005];
dist = new int[100005];
for (int i = 0; i < m; ++i) {
int u = nextInt();
int v = nextInt();
int w = nextInt();
add(u, v, w);
}
dijkstra();
for (int i = 1;i <= n;i++) System.out.print(dist[i]+" ");
}
private static void dijkstra() {
Arrays.fill(dist, MAX);
dist[s] = 0;
PriorityQueue<Node> que = new PriorityQueue<>(cmp);
que.add(new Node(s, 0));
while (!que.isEmpty()) {
Node p = que.poll();
int u = p.u;
if (vis[u]) continue;
vis[u] = true;
for (int i = head[u]; i > 0; i = e[i].next) {
int v = e[i].v, w = e[i].w;
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
if (vis[v] == false)
que.add(new Node(v, dist[v]));
}
}
}
}
private static void add(int from, int to, int w) {
e[++cnt] = new Edge();
e[cnt].v = to;
e[cnt].w = w;
e[cnt].next = head[from];
head[from] = cnt;
}
static class Edge {
int v, w, next;
}
}
class Node {
int u, d;
public Node(int u, int d) {
this.u = u;
this.d = d;
}
}