迪杰斯特拉算法实现单源最短路
使用了 邻接表来存放图的信息,使用了优先级队列。
#include <iostream>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int inf = 1 << 26;
struct qnode
{
int v;
int c;
qnode(int _v = 0, int _c = 0) :v(_v), c(_c) {}
bool operator <(const qnode &r)const //反顺序,则从小到大
{
return c > r.c;
}
};
struct Edge
{
int v, cost;
Edge(int _v = 0, int _cost = 0) :v(_v), cost(_cost) {}
};
vector<Edge>E[100];
bool vis[100];
int dist[100];
void Dijkstra(int n, int start)//点的编号从1开始
{
memset(vis, false, sizeof(vis));
for (int i = 1; i <= n; i++)dist[i] = inf;
priority_queue<qnode>que; //大顶堆(降序),队头元素最大
while (!que.empty()) que.pop();
dist[start] = 0;
que.push(qnode(start, 0));
qnode tmp;
while (!que.empty())
{
tmp = que.top();
que.pop();
int u = tmp.v;//点
if (vis[u])continue;
vis[u] = true;
for (int i = 0; i < E[u].size(); i++)
{
int v = E[u][i].v;//u邻接到的点
int cost = E[u][i].cost;
if (!vis[v] && dist[v] > dist[u] + cost)
{
dist[v] = dist[u] + cost;
que.push(qnode(v, dist[v]));
}
}
}
}
int main()
{
int n, m,a,b,w;
Edge e;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
cin >> a >> b >> w;
e.v = b;
e.cost = w;
E[a].push_back(e);
e.v = a;
e.cost = w;
E[b].push_back(e);
}
Dijkstra(n, 1);
for (int i = 1; i <= n; i++) {
cout << dist[i] << " "; //点1 到其他点的最短路径
}
return 0;
}