朴素版的dijkstra求最短路
#include <bits/stdc++.h>
using namespace std;
const int N = 510;
int g[N][N], dist[N];
int n, m;
bool st[N];
int dijkstra()
{
memset(dist, 0x3f3f3f3f, sizeof dist);
dist[1] = 0;
for (int i = 0; i < n; i++)
{
int t = -1;
for (int j = 1; j <= n; j++)
{
if (!st[j] && (t == -1 || dist[j] < dist[t]))
{
t = j;
}
}
st[t] = true;
for (int j = 1; j <= n; j++)
{
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
}
if (dist[n] == 0x3f3f3f3f)
return -1;
else
return dist[n];
}
int main()
{
memset(g, 0x3f, sizeof g);
cin >> n >> m;
while (m--)
{
int a, b, c;
cin >> a >> b >> c;
g[a][b] = min(g[a][b], c);
}
cout << dijkstra();
return 0;
}
堆优化的dijkstra
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n, m, h[N], w[N], e[N], ne[N], idx;
int dis[N];
bool st[N];
typedef pair<int, int> PII;
void ClearFloat()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int dijkstra()
{
memset(dis, 0x3f3f3f3f, sizeof(dis));
dis[1] = 0;
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, 1});
while (heap.size())
{
PII t = heap.top();
heap.pop();
int ver = t.second, dist = t.first;
if (st[ver])
continue;
st[ver] = 1;
for (int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i];
if (dis[j] > dis[ver] + w[i])
{
dis[j] = dis[ver] + w[i];
heap.push({dis[j], j});
}
}
}
if (dis[n] == 0x3f3f3f3f)
return -1;
return dis[n];
}
int main()
{
ClearFloat();
cin >> n >> m;
memset(h, -1, sizeof(h));
for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
cout << dijkstra() << '\n';
return 0;
}