您的位置:首页 > 其它

基于邻接表和优先级队列的Dijkstra算法实现

2013-06-20 12:03 441 查看
/*基于邻接表和优先级队列的Dijkstra算法实现
* */
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

class Node {
int value;
int num;

public Node(int value, int num) {
super();
this.value = value;
this.num = num;
}
}

class NodeComparator implements Comparator<Node> {

@Override
public int compare(Node o1, Node o2) {
if (o1.value > o2.value)
return 1;
else if (o1.value < o2.value)
return -1;
else {
if (o1.num < o2.num)
return -1;
else if (o1.num > o2.num)
return 1;
}
return 0;
}
}

public class DijkstraALPQ {
static final int MAX = 1 << 20;

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int[] first = new int
;// first[u]保存节点u的第一条边的编号
int[] u = new int[m];// u[i]第i条边的起点编号
int[] v = new int[m];
int[] w = new int[m];
int[] next = new int[m];// next[e]表示编号为e的边的下一条边
int[] d = new int
;// d[i]表示节点0到节点i的最短距离
int[] vis = new int
;
int[] fa = new int
;
Arrays.fill(first, -1);// 初始化表头
for (int e = 0; e < m; e++) {
u[e] = scanner.nextInt();
v[e] = scanner.nextInt();
w[e] = scanner.nextInt();
next[e] = first[u[e]];// 插入链表
first[u[e]] = e;
}
Arrays.fill(d, MAX);
d[0] = 0;
PriorityQueue<Node> q = new PriorityQueue<Node>(n, new NodeComparator());
q.offer(new Node(d[0], 0));
while (q.size() > 0) {
Node node = q.poll();
int x = node.num;
if (vis[x] == 1)
continue;
vis[x] = 1;
for (int e = first[x]; e != -1; e = next[e]) {
if (d[v[e]] > d[x] + w[e]) {
d[v[e]] = d[x] + w[e];
fa[v[e]] = x;// 保留父节点
}
q.offer(new Node(d[v[e]], v[e]));
}
}
for (int i = 0; i < n; i++) {
if (i == 0) {
System.out.println(0);
continue;
} else {
System.out.printf("%d<-", i);
int t = fa[i];
while (t > 0) {
System.out.printf("%d<-", t);
t = fa[t];
}
}
System.out.println(0 + "  the minmum length is " + d[i]);
}
}
}


输入:
6
11
0 1 20
0 2 60
0 4 10
0 5 65
1 2 30
1 3 70
2 3 40
3 4 35
4 5 20
5 2 40
5 3 80
输出:
0
1<-0  the minmum length is 20
2<-1<-0  the minmum length is 50
3<-1<-0  the minmum length is 90
4<-0  the minmum length is 10
5<-4<-0  the minmum length is 30
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: