dijkstra 代码基本结构:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
#define INF INT_MAX // 无穷大
// 定义图的边
struct Edge {
int to;
int weight;
Edge(int t, int w) : to(t), weight(w) {}
};
// 定义图的顶点
struct Vertex {
vector<Edge> edges; // 顶点的邻接边
};
// Dijkstra 算法
void dijkstra(vector<Vertex>& graph, int start, vector<int>& dist) {
int n = graph.size();
dist.assign(n, INF); // 初始化距离数组为无穷大
dist[start] = 0; // 起始点到自身的距离为 0
// 优先队列存放顶点,按距离从小到大排序
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, start}); // 将起始点加入队列
while (!pq.empty()) {
int u = pq.top().second;
int d = pq.top().first;
pq.pop();
if (d > dist[u]) continue; // 已经找到了更短的路径,跳过
// 遍历当前顶点的所有邻接边
for (const Edge& e : graph[u].edges) {
int v = e.to;
int w = e.weight;
// 如果通过当前顶点 u 到顶点 v 的距离比之前的距离短,则更新距离数组并将 v 加入队列
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
}
int main() {
// 例子:有向带权图的邻接表表示
int n = 6; // 顶点数
vector<Vertex> graph(n);
// 添加边
graph[0].edges.push_back(Edge(1, 5));
graph[0].edges.push_back(Edge(2, 3));
graph[1].edges.push_back(Edge(3, 6));
graph[1].edges.push_back(Edge(4, 7));
graph[2].edges.push_back(Edge(3, 2));
graph[2].edges.push_back(Edge(4, 4));
graph[3].edges.push_back(Edge(5, 5));
graph[4].edges.push_back(Edge(5, 3));
// Dijkstra 算法计算从顶点 0 到其他顶点的最短距离
vector<int> dist;
dijkstra(graph, 0, dist);
// 输出结果
for (int i = 0; i < n; ++i) {
cout << "Distance from 0 to " << i << ": ";
if (dist[i] == INF) cout << "INF" << endl;
else cout << dist[i] << endl;
}
return 0;
}
例题:
R155902262
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
struct edge{
int to,value;
};
struct vertex{
vector<edge> edges;
};
void dijkstra(vector<vertex>& f,int sta,int n,vector<int>& g)
{
g.assign(n+1,inf);
g[sta]=0;
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> qu;
qu.push({0,sta});
while(!qu.empty())
{
int d,u;
d=qu.top().first;
u=qu.top().second;
qu.pop();
if(d>g[u]) continue;
for(const auto&e:f[u].edges)
{
int nd=e.value;
int nu=e.to;
if(g[nu]>g[u]+nd)
{
g[nu]=g[u]+nd;
qu.push({g[nu],nu});
}
}
}
}
int main()
{
int n,m,s;
cin>>n>>m>>s;
vector<vertex> f(n+1);
vector<int> g;
for(int i=0;i<m;i++)
{
int a,b,c;
cin>>a>>b>>c;
f[a].edges.push_back({b,c});
}
dijkstra(f,s,n,g);
for(int i=0;i<n;i++)
{
cout<<g[i+1]<<" ";
}
return 0;
}