1.Bellman-Ford O(nm)
#include <bits/stdc++.h>
using namespace std;
const int N = 510, M = 10010;
int n, m, k;
int dist[N], temp[N];
struct
{
int a, b, w;
} g[M];
void f()
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
for (int i = 1; i <= k; i ++)
{
memcpy(temp, dist, sizeof dist);
for (int j = 1; j <= m; j ++)
{
int x = g[j].a, y = g[j].b, z = g[j].w;
dist[y] = min(dist[y], temp[x] + z);
}
}
if (dist[n] > 0x3f3f3f3f / 2) cout << "impossible" << endl;
else cout << dist[n] << endl;
}
int main()
{
cin.tie(0), cout.tie(0);
cin >> n >> m >> k;
for (int i = 1; i <= m; i ++ )
{
int a ,b, c;
cin >> a >> b >> c;
g[i] = {a, b, c};
}
f();
return 0;
}
对于Bellman-Ford算法,我们只需要知道所有的边和权,而不需要一定的对应关系,所以只需要用结构体来存储即可;
2.spfa 平均O(m) 最坏O(nm)
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int h[N], w[N], e[N], ne[N], idx;
int n, m;
int dist[N];
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
void spfa()
{
queue<int> q;
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
q.push(1);
st[1] = 1;
while (!q.empty())
{
int t = q.front();
q.pop();
st[t] = 0;
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
if (!st[j])
{
q.push(j);
st[j] = 1;
}
}
}
}
if (dist[n] > 0x3f3f3f3f / 2) puts("impossible");
else cout << dist[n] << endl;
}
int main()
{
cin.tie(0), cout.tie(0);
memset(h, -1, sizeof h);
cin >> n >> m;
while (m -- )
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
spfa();
return 0;
}
在最后不能以-1来判断是否有解,因为解有可能为-1;