欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 19840 Dijkstra求最短路2

19840 Dijkstra求最短路2

2025/4/2 9:12:59 来源:https://blog.csdn.net/2301_76979886/article/details/146713592  浏览:    关键词:19840 Dijkstra求最短路2

19840 Dijkstra求最短路2

相较于1,数据增强了,要用堆来优化,也就是优先队列。

⭐️难度:中等
🌟考点:Dijkstra、最短路问题
📖
在这里插入图片描述

📚

import java.util.*;public class Main {static int N = 100005;static int n;final static int INF = 0x3f3f3f3f;  // 一个足够大的数,同时确保不会超intstatic int[] dis = new int[N]; // 记录 点1 到每个人的最短距离static boolean[] vis = new boolean[N]; // 记录 该点是否已经被访问static ArrayList<int[]>[] g = new ArrayList[N]; // 语法注意public static void main(String[] args) {Scanner sc = new Scanner(System.in);n = sc.nextInt();int m = sc.nextInt();for (int i = 0; i < m; i++) {int a = sc.nextInt();int b = sc.nextInt();int c = sc.nextInt();addEdge(a,b,c);}dijkstra(1);System.out.println(dis[n] == INF ? -1 : dis[n]);}// 加边static void addEdge(int u, int v, int w) {if (g[u] == null) g[u] = new ArrayList<>();g[u].add(new int[]{v, w});  // 语法注意}// Dijkstrastatic void dijkstra(int s){Arrays.fill(dis,INF); // 一开始标记为 所有点都不可达dis[s] = 0;PriorityQueue<int[]> q = new PriorityQueue<>(Comparator.comparingInt(e->e[1]));  // 比较数组的第二个元素,也就是边的权值,注意语法q.add(new int[]{s,0}); // 注意语法while(!q.isEmpty()){int[] cur = q.poll(); // 优先队列已经把权值按升序排好,只管取队头int u = cur[0];if(vis[u] == true) continue; // 若该店访问过,跳过vis[u] = true; // 标记为已访问if(g[u] == null) continue; // 改 点u 没有可指向边,跳过for(int[] e : g[u]){int v = e[0];  // 取点int w = e[1];  // 取权值if(dis[v] > dis[u] + w){dis[v] = dis[u] + w; // 刷新 点1 到 点v 的最近距离q.add(new int[]{v,dis[v]}); // 与 点u 相连的点入队列}}}}
}

🍎笔记
在这里插入图片描述
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词