用链式前向星存储有关边的信息,无向有权图的存储方式 具体见下图所示:
题目要求的是有向有权图可以在上面的基础上稍作修改即可
大佬的解析
代码如下:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
const int MAXN = 100010, MAXM = 300010;
struct edge {
int to, dis, next;
};
edge e[MAXM];
int head[MAXN], length[MAXN], cnt; //length[i] = x 表示s到i的路径长为x
bool vis[MAXN]; //vis[i] = 1表示s到i已经确定了最短路径
int n, m, s;
inline void add_edge(int u, int v, int d) {
cnt++; //cnt为每条边的编号
e[cnt].to = v;
e[cnt].dis = d;
e[cnt].next = head[u];
head[u] = cnt;
}
struct node {
int pos;
int dis;
bool operator <(const node &t) const {
return dis > t.dis;
}
}temp;
priority_queue<node> que;
inline void dijkstra() {
length[s] = 0; //自己到自己的路径长为0
temp.pos = s;
temp.dis = 0;
que.push(temp);
while (!que.empty()) {
temp = que.top();
que.pop();
int cur_pos = temp.pos;
if (vis[cur_pos]) continue;
vis[cur_pos] = 1;
for(int i = head[cur_pos]; i; i = e[i].next) { //i表示某条边的编号
int y = e[i].to;
if (length[y] > length[cur_pos] + e[i].dis) {
length[y] = length[cur_pos] + e[i].dis;
temp.pos = y;
temp.dis = length[y];
que.push(temp);
}
}
}
}
int main()
{
cin >> n >> m >> s;
for(int i = 1; i <= n; i++) length[i] = INT_MAX;
for(int i = 0; i < m; i++) {
int u, v, d;
cin >> u >> v >> d;
add_edge(u, v, d);
}
dijkstra();
for(int i = 1; i <= n; i++) cout << length[i] << " ";
return 0;
}