模板 Dijkstra
该题是基于堆优化的Dijkstra算法。原理:Dijkstra算法求dis数组的最小值时正常需要O(n)的复杂度,而用堆排的动态排序的性能可以降到log(n)的复杂度
本人写的原始O(n)的复杂度的算法一直都有点问题(主要在寻找最小值的过程中可能回出现Bug)所以只分享优化的算法 = =!
在这里声明:在洛谷的模板也不能全通过,因为用java,内存可能偏大的原因
如果是个人算法错误欢迎指点
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;
class ArcNode{ //邻接表类
public int adjV;
public long value;
public ArcNode nextArc;
public ArcNode(int adjV) {
this(adjV, -1, null);
}
public ArcNode(int adjV, long value, ArcNode nextArc) {
this.adjV = adjV;
this.value = value;
this.nextArc = nextArc;
}
}
class Node implements Comparable<Node>{
public int node;
public long dis;
public Node(int node, long dis) {
this.node = node;
this.dis = dis;
}
public int compareTo(Node o) {
if(this.dis > o.dis)
return 1;
if(this.dis < o.dis)
return -1;
return 0;
}
}
public class 单源最短路径2 {
public static ArcNode[] e = new ArcNode[100005]; //各个点的邻接表
public static boolean[] vis = new boolean[100005]; //数组标记该点是否查询
public static long[] dis = new long[100005];
public static long maxint = Long.MAX_VALUE;
public static PriorityQueue<Node> q = new PriorityQueue<Node>();
public static void dijkstra(int n, int s) {
Arrays.fill(dis, 1, n+1, maxint);
q.add(new Node(s, 0));
dis[s] = 0;
while(!q.isEmpty()) {
int x = q.poll().node;
//System.out.println(x);
ArcNode An = e[x].nextArc;
if(vis[x]) continue;
vis[x] = true;
for( ;An != null; An = An.nextArc) {
int y = An.adjV;
long z = An.value;
//System.out.println("y="+y);
//System.out.println("z="+z);
if(dis[y] > dis[x]+z) {
dis[y] = dis[x]+z;
q.add(new Node(y, dis[y]));
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int s = sc.nextInt(); //源点
for(int i = 1; i <= n; i++) {
e[i] = new ArcNode(i);
}
for(int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
ArcNode d = e[a];
while(d.nextArc != null) {
d = d.nextArc;
}
d.nextArc = new ArcNode(b, c, null);
}
dijkstra(n, s);
for(int i = 1; i <= n; i++) {
if(vis[i]) System.out.print(dis[i]+" ");
else System.out.print(2147483647+" ");
}
}
}