AcWing----850. Dijkstra seeking the shortest path II (Java)_heap optimization Dijkstra_Dijkstra algorithm_edge weight is positive

Original title link

①. Title

Insert picture description here

②. Thinking

  • Dijkstra algorithm uses breadth-first search to solve the single-source shortest path problem of weighted directed graphs or undirected graphs, and the algorithm finally obtains a shortest path tree. This algorithm is often used in routing algorithms or as a sub-module of other graph algorithms.
    Insert picture description hereInsert picture description here
  • Dense graphs are stored using adjacency matrix
  • 稀疏图使用邻接表存储

③. Learning points

堆优化Dijkstra

④. Code implementation

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;
	}
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45480785/article/details/114106666