【模板】Dijkstra

模板 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+" ");
		}
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值