bellman_ford的邻接表实现
作者:
Soel
,
2023-03-12 16:46:10
,
所有人可见
,
阅读 141
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1e6 + 10;
int h[N], e[N], ne[N], idx;
int w[N];
int n, m, k;
int dist[N];
int last[N];
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c;
h[a] = idx++;
}
void bellman_ford()
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
for (int i = 0; i < k; i++) {
memcpy(last, dist, sizeof dist);
for (int j = 1; j <= n; j++)
for (int t = h[j]; ~t; t = ne[t]) {
int k = e[t];
dist[k] = min(dist[k], last[j] + w[t]);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
cin >> k;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
bellman_ford();
if (dist[n] > 0x3f3f3f3f / 2) cout << "impossible\n";
else cout << dist[n];
return 0;
}