所以我正在实现Dijkstra的算法,我在尝试减少它的运行时遇到了麻烦。理想情况下,O(M log N)运行时会很棒。
这是我的代码:
import static jdk.nashorn.internal.runtime.regexp.joni.Syntax.Java;
import java.util.Scanner;
public class Dijkstra {
public static void main(String[] args) {
int [][] A = new int[50010][60];
int [][] W = new int[50010][60];
int [] deg = new int[50010];
int N, M, S;
Scanner scan = new Scanner(System.in);
N = scan.nextInt(); // # cities
M = scan.nextInt(); // # train routes
S = scan.nextInt(); // capital city
// System.out.println(N + " " + M + " " + S);
for(int i = 1; i <=N; ++i) {
deg[i] = 0; // initialize the degree of each vertex to 0
}
for(int i = 1; i <= M; ++i) {
int u, v, w;
u = scan.nextInt(); // origin
v = scan.nextInt(); // destination
w = scan.nextInt(); // # days
// System.out.println(u + " " + v + " " + w);
A[u][deg[u]] = v; // adding an edge (u,v) to the graph
W[u][deg[u]] = w; // set its weight to w
deg[u]++; // increase degree of vertex u by 1
}
//for(int i = 1; i <= N; ++i) {
// System.out.println("vertex:" + i + "'s neighbors");
// for(int j = 0; j < deg[i]; ++j) {
// System.out.println(A[i][j] + " " + W[i][j]);
// }
//}
// compute distance from U to S by Dijkstra's algorithm
// Dijkstra's algorithm
for(int U = 1; U <= N; ++U) {
// initialization
int[] visited = new int[50010];
int[] dist = new int[50010];
for(int V = 1; V <= N; ++V) {
dist[V] = 100000000;
visited[V] = 0;
}
// actual algorithm
dist[U] = 0;
for(int k = 1; k <= N; ++k) {
// repeat the following N times
//find an unvisited vertex with minimum distance
int min = 100000000;
int minVertex = 1;
for(int i = 1; i<=N; ++i) {
if(visited[i] == 0 && dist[i] < min) {
min = dist[i];
minVertex = i;
}
}
visited[minVertex] = 1;
// relax the edges that are adjacent to minVertex to update the shortest path distance to
// neighbors of minVertex
for(int j = 0; j<deg[minVertex]; ++j) {
// A[minVertex][j] is the j-th neighbor of minVertex
// W[minVertex][j] is the weight of the corresponding edge
int newDist = dist[minVertex] + W[minVertex][j];
if (newDist < dist[A[minVertex][j]]) {
dist[A[minVertex][j]] = newDist;
}
}
}
if(dist[S] == 100000000) {
System.out.print("-1 ");
}
else {
System.out.print(dist[S] + " ");
}
}
System.out.println("");
}
}
我无法让它在O(M log N)时间运行。我知道我必须在某个地方实施堆,但我不知道在哪里。
非常感谢任何帮助。