实用指南:【Dijkstra】 Shortest Routes I

题目描述

There are n cities and m flight connections between them. Your task is to determine the length of the shortest route from Syrjälä to every city.

输入

The first input line has two integers n and m: the number of cities and flight connections. The cities are numbered 1,2,...,n, and city 1 is Syrjälä.
After that, there are m lines describing the flight connections. Each line has three integers a, b and c: a flight begins at city a, ends at city b, and its length is c. Each flight is a one-way flight.
You can assume that it is possible to travel from Syrjälä to all other cities.
Constraints
1 ≤ n ≤ 105
1 ≤ m ≤ 2*105
1 ≤ a,b ≤ n
1 ≤ c ≤ 109

输出

Print n integers: the shortest route lengths from Syrjälä to cities 1,2,...,n.

样例输入

复制

3 4
1 2 6
1 3 2
3 2 3
1 3 4
样例输出

复制

0 5 2

题目描述:
有 n 个城市和 m 条航班连接它们。你的任务是确定从 Syrjälä 到每个城市的最短路线长度。

输入:
第一行输入有两个整数 n 和 m:分别表示城市的数量和航班连接的数量。城市编号为 1、2、…、n,其中城市 1 是 Syrjälä。
接下来有 m 行,描述航班连接。每行有三个整数 a、b 和 c:表示一趟航班从城市 a 出发,到达城市 b,飞行长度为 c。每趟航班都是单向的。
可以保证从 Syrjälä 能够到达所有其他城市。

约束条件:
1 ≤ n ≤ 10^5
1 ≤ m ≤ 2*10^5
1 ≤ a,b ≤ n
1 ≤ c ≤ 10^9

输出:
输出 n 个整数:分别表示从 Syrjälä 到城市 1、2、…、n 的最短路线长度。

迪杰斯特拉算法(Dijkstra's Algorithm)是一种用于求解带权有向图或无向图中从单个源点到其他所有顶点的最短路径的经典算法。它要求图中所有边的权重为非负数(若存在负权边,需使用贝尔曼 - 福特算法等其他方法)。

具体步骤(以源点为 S 为例)

  1. 初始化数据结构

    • 记录各顶点到源点 S 的最短距离(记为 dist[]):
      • dist[S] = 0(源点到自身的距离为 0);
      • 其他顶点的 dist[] 初始化为 无穷大(∞)(表示初始时未知距离)。
    • 记录顶点是否已确定最短路径(记为 visited[]):所有顶点初始化为 false(未确定)。
    • 优先队列(最小堆):用于高效获取 “当前距离源点最近且未确定路径的顶点”。
  2. 将源点加入优先队列
    把 (dist[S], S) 即 (0, S) 放入优先队列,开始迭代。

  3. 迭代确定最短路径
    重复以下步骤,直到优先队列为空(所有顶点都确定了最短路径):

    • 步骤 1:取出距离源点最近的未确定顶点
    • 步骤 2:标记顶点 u 的最短路径为确定
    • 步骤 3:更新相邻顶点的距离
  4. 输出结果

代码

#include
using namespace std;
typedef long long ll;
typedef pair P;
const int N=1e5+10;
int n,m;
vector>adj(N);
vectordis(N,LLONG_MAX);
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n>>m;
for(int i=0;i>a>>b>>c;
adj[a].push_back({b,c});
}
priority_queue,greater>q;
vectorc(N,0);
q.push({0,1});
dis[1]=0;
while(!q.empty())
{
ll d=q.top().first;
ll u=q.top().second;
q.pop();
if(c[u])continue;//优化时间
c[u]=1;
for(auto i:adj[u])
{
ll v=i.first;
ll l=i.second;
if(dis[v]>dis[u]+l)
{
dis[v]=dis[u]+l;
q.push({dis[v],v});
}
}
}
for(int i=1;i<=n;++i)cout<

posted @ 2025-08-10 10:49  yfceshi  阅读(14)  评论(0)    收藏  举报