Dijstra最短路算法
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 500010;
typedef pair<int, int> PII;
#define x first
#define y second
int n, m;
bool st[N];
int dist[N];
int h[N], e[N], w[N], ne[N], idx;
void add(int a, int b, int c)
{
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx ++;
}
int dijstra()
{
// 初始化距离
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
// 定义一个小根堆
priority_queue<PII, vector<PII>, greater<PII>> q;
q.push({0, 1});
while (!q.empty())
{
auto t = q.top();
q.pop();
int id = t.y, d = t.x;
if (st[id] == true)
continue;
st[id] = true;
for (int i = h[id]; ~i; i = ne[i])
{
int j = e[i];
if (dist[j] > d + w[i])
{
dist[j] = d + w[i];
q.push({ dist[j], j });
}
}
}
if (dist[n] == 0x3f3f3f3f)
return -1;
return dist[n];
}
int main()
{
int a, b, c;
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while (m -- )
{
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
printf("%d\n", dijstra());
return 0;
}
bellman_ford算法
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 500010;
const int INF = 0x3f3f3f3f;
int n, m, k;
int dist[N];
int copys[N];
struct Edge
{
int a, b, w;
}edge[N];
int bellman_ford()
{
/**初始化距离**/
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
for (int i = 0; i < k; i ++ )
{
memcpy(copys, dist, sizeof dist);
for (int j = 0; j < m; j ++ )
{
int a = edge[j].a;
int b = edge[j].b;
int w = edge[j].w;
dist[b] = min(dist[b], copys[a] + w);
}
}
if (dist[n] > INF / 2)
return -1;
return dist[n];
}
int main()
{
int a, b, w;
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < m; i ++ )
{
scanf("%d%d%d", &a, &b, &w);
edge[i] = {a, b, w};
}
int res = bellman_ford();
if ((res == -1) && (dist[n] != -1))
puts("impossible");
else
printf("%d\n", res);
return 0;
}