#include <iostream>
#include <cstring>
using namespace std;
struct edge { //记录每条边信息
int s; //边的起点
int e; //边的终点
int v; //边的权值
};
edge edg[200005];
int n; //点的数量
int m; //边的数量
int s; //起点
int cnt, ans[100005]; //存储最短路径
void addEdg(int a, int b, int c)
{
edg[cnt].s = a;
edg[cnt].e = b;
edg[cnt].v = c;
}
int main()
{
memset(ans, 0x3F, sizeof(ans)); //0x3F表示就算乘以2不会越界,值等价于0x3F3F3F3F
cin >> n >> m >> s; //怕超时可以改成scanf()
for (int i = 0; i < m; ++i) {
int a, b, c; //起点为a,终点为b,权值为c
cin >> a >> b >> c;
addEdg(a, b, c);
addEdg(b, a, c);
}
ans[s] = 0;
for (int i = 1; i <= n; ++i) {
int f = 0;
for (int j = 0; j < cnt; ++j) {
int s = edg[j].s, e = edg[j].e, v = edg[j].v;
if (ans[e] > ans[s] + v) {
ans[e] = ans[s] + v;
f = 1;
}
}
if (0 == f) break;
}
for (int i = 1; i <= n; ++i)
if (0x3F3F3F3F == ans[i]) cout << -1 << endl;
else cout << ans[i] << endl;
return 0;
}
基于队列优化的Bellman-Ford算法
时间复杂度和Dijkstra算法相当,但不稳定最坏时间复杂度O(n * m)
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
struct edge { //记录每条边信息
int e; //边的终点
int v; //边的权值
int next;
};
edge edg[200005];
int n; //点的数量
int m; //边的数量
int s; //起点
int ans[100005]; //存储最短路径
int head[100005]; //保留以每个点出发的所有边当中最后一条边所在edg下标
int cnt, mark[100005]; //标记数组去重 在队列中为1,不在队列中为0
void addEdg(int a, int b, int c)
{
edg[cnt].e = b;
edg[cnt].v = c;
edg[cnt].next = head[a];
head[a] = ++cnt;
}
int main()
{
memset(ans, 0x3F, sizeof(ans)); //0x3F表示就算乘以2不会越界,值等价于0x3F3F3F3F
memset(head, -1, sizeof(head));
cin >> n >> m >> s; //怕超时可以改成scanf()
for (int i = 0; i < m; ++i) {
int a, b, c; //起点为a,终点为b,权值为c
cin >> a >> b >> c;
addEdg(a, b, c);
addEdg(b, a, c);
}
//开始算法
queue<int> que;
que.push(s);
ans[s] = 0;
while (!que.empty()) {
int tmp = que.front();
que.pop();
mark[tmp] = 0; //出队标记为0
for (int i = head[tmp]; i != -1; i = edg[i].next) { //遍历以这个点为起点的所有边
int e = edg[i].e, v = edg[i].v;
if (ans[e] > ans[tmp] + v) {
ans[e] = ans[tmp] + v;
if (0 == mark[e]) {
mark[e] = 1;
que.push(e);
}
}
}
}
for (int i = 1; i <= n; ++i)
if (0x3F3F3F3F == ans[i]) cout << -1 << endl;
else cout << ans[i] << endl;
return 0;
}