AcWing----850. Dijkstra求最短路 II (Java)_堆优化Dijkstra_迪杰斯特拉算法_边权值为正

原题链接

①. 题目

在这里插入图片描述

②. 思路

  • Dijkstra算法使用了广度优先搜索解决赋权有向图或者无向图的单源最短路径问题,算法最终得到一个最短路径树。该算法常用于路由算法或者作为其他图算法的一个子模块。
    在这里插入图片描述在这里插入图片描述
  • 稠密图使用邻接矩阵存储
  • 稀疏图使用邻接表存储

③. 学习点

堆优化Dijkstra

④. 代码实现

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;

public class Main {
    
    
	/*
	 * 使用堆优化dijkstra 
	 */
	
	static int n=0,m=0,N=1000010;
	//使用优先队列 对距离进行从小到大排序
	static PriorityQueue<int[]> q=new PriorityQueue<>((a,b)-> {
    
    return a[1]-b[1];});
	static int[] dist=new int[N];  //存储所有节点到起点的最短距离
	static boolean[] f=new boolean[N]; //标记节点最短距离是否确定
	//使用邻接表存图 稀疏图
	static int[] h=new int[N],e=new int[N],ne=new int[N],w=new int[N];
	static int idx=1;
	public static void main(String[] args) throws IOException {
    
    
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] s = br.readLine().split(" ");
		n=Integer.parseInt(s[0]);
		m=Integer.parseInt(s[1]);
		Arrays.fill(h, -1); //链表头结点都存放-1
		for(int i=1;i<=m;i++) {
    
    
			String[] s2 = br.readLine().split(" ");
			int a=Integer.parseInt(s2[0]);
			int b=Integer.parseInt(s2[1]);
			int c=Integer.parseInt(s2[2]);
			add(a,b,c);
		}
		System.out.println(dijkstra());
	}
	
	//邻接表存储图模板
	static void add(int a,int b,int c) {
    
    
		e[idx]=b;
		w[idx]=c;
		ne[idx]=h[a];
		h[a]=idx++;
	}
	
	static int dijkstra() {
    
    
		Arrays.fill(dist, 0x3f3f3f3f);
		dist[1]=0;  //自己到自己的距离为0
		q.offer(new int[] {
    
    1,0}); //将第一个节点和最短距离加入优先队列(小堆)
		while(q.size()!=0) {
    
    
			int[] a=q.poll();
			int t=a[0],distance=a[1];
			//若该点操作过 直接跳过
			if(f[t]) {
    
    
				continue;
			}
			//当前节点的最小距离已经找到
			f[t]=true;
			//遍历该节点的链表
			for(int i=h[t];i!=-1;i=ne[i]) {
    
    
				int j=e[i];
				//若出现更小的距离 直接更新
				if(dist[j]>distance+w[i]) {
    
    
					dist[j]=distance+w[i];
					//加入到队列中去
					q.offer(new int[] {
    
    j,dist[j]});
				}
			}
		}
		//判断路径是否存在
		  if(dist[n] != 0x3f3f3f3f)return dist[n];
	        return -1;
	}
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45480785/article/details/114106666