一. 最短路问题
1. dijkstra
(1). 朴素版dijkstra O(n^2)
#include <bits/stdc++.h>
using namespace std;
const int N = 3000;
int g[N][N], dist[N];
int n, m, s, e;
bool st[N];
int dijkstra(int s, int e)
{
memset(dist, 0x3f, sizeof dist);
dist[0] = 0;
for (int i = 0; i < n - 1; i++)
{
int t = -1;
for (int j = 1; j <= n; j++)
if (!st[j] && (t == -1) || (dist[t] > dist[j]))
t = j;
st[t] = true;
for (int j = 1; j <= n; j++)
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
return dist[e];
}
int main()
{
cin >> n >> m >> s >> e;
memset(g, 0x3f, sizeof g);
for (int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = min(c, g[a][b]);
}
int t = dijkstra(s, e);
cout << t << endl;
return 0;
}
(2). 堆优化dijkstra O((n+m)logm)
#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
const int N = 3010, M = 20010;
typedef pair<int, int>PII;
int h[N], e[M], ne[M], w[M], idx;
bool st[N];
int dist[M];
int n, m, s, d;
priority_queue<PII, vector<PII>, greater<PII>>heap;
void add(int a, int b, int c)
{
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
int dijkstra(int s, int d)
{
memset(dist, 0x3f, sizeof dist);
dist[s] = 0;
heap.push({ dist[s],s });
while (heap.size())
{
auto t = heap.top();
heap.pop();
if (st[t.y])continue;
st[t.y] = true;
for (int i = h[t.y]; ~i; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[t.y] + w[i])
{
dist[j] = dist[t.y] + w[i];
heap.push({ dist[j], j });
}
}
}
return dist[d];
}
int main()
{
cin >> n >> m >> s >> d;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
int t = dijkstra(s, d);
cout << t << endl;
return 0;
}
2. spfa O(n*m)
关于spfa 它已经死了
#include <bits/stdc++.h>
using namespace std;
const int N = 3000, M = 20000;
int h[N], e[M], ne[M], w[M], idx;
bool st[N];
int dist[M];
int n, m, s, d;
void add(int a, int b, int c)
{
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
int spfa(int s, int d)
{
memset(dist, 0x3f, sizeof dist);
dist[s] = 0;
queue<int>q;
q.push(s);
st[s] = true;
while (q.size())
{
auto t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
if (!st[j])
{
st[j] = true;
q.push(j);
}
}
}
}
return dist[d];
}
int main()
{
cin >> n >> m >> s >> d;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
int t = spfa(s, d);
cout << t << endl;
return 0;
}