题目:
代码:
Floyd算法:O(n3)
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2e2 + 10, inf = 0x3f3f3f3f;
int d[N][N];
int n, m, q;
void floyd ()
{
for (int k=0; k < n; k ++)
for (int i=0; i < n; i ++)
for (int j=0; j < n; j ++)
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}
int main()
{
while (scanf("%d%d", &n, &m) != EOF)
{
for (int i=0; i < n; i ++)
{
for (int j=0; j < n; j ++)
{
if (i == j) d[i][j] = 0;
else d[i][j] = inf;
}
}
while (m -- )
{
int a, b, c;
cin >> a >> b >> c;
d[a][b] = min(d[a][b], c);
d[b][a] = d[a][b];
}
floyd ();
int s, t;
cin >> s >> t;
if (d[s][t] == inf) cout << -1 << endl;
else cout << d[s][t] << endl;
}
return 0;
}
朴素版:Djkstra算法:O(n^2);
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2e2 + 10, inf = 0x3f3f3f3f;
int n, m;
int d[N][N]; //邻接矩阵
bool st[N]; //已经确定最短路的就不能够再访问了
int dist[N]; //已经确定了
int s, t;
int dj ()
{
memset (st, false, sizeof (st)); //标记没有走过!
memset (dist, 0x3f, sizeof (dist));
dist[s] = 0;
for (int i=0; i < n-1; i ++)
{
int t = -1;
for (int j=0; j < n; j ++)
if (!st[j] && (t == -1 || dist[j] < dist[t]))
t = j;
st[t] = true;
for (int j=0; j < n; j ++)
{
dist[j] = min(dist[t] + d[t][j], dist[j]);
}
}
return dist[t]==inf ? -1:dist[t];
}
int main()
{
while (scanf ("%d%d", &n, &m) != EOF)
{
//初始化邻接矩阵:
for (int i=0; i < n; i ++)
for (int j=0; j < n; j ++)
d[i][j] = i==j ? 0 : inf;
while (m -- )//m条边:
{
int a, b, x;
cin >> a >> b >> x;
d[a][b] = d[b][a] = min(d[a][b], x);
}
scanf("%d%d", &s, &t);
cout << dj() << endl;
}
return 0;
}
堆优化版本:Djkstra算法:O(m*logN):
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 200, M = 1e3 + 10;
int h[N], e[M], ne[M], idx;
int n, m;
int dist[N], w[M]; //dist[i]:表示i号点到达源点的最短路径距离!
bool st[N]; //st[i]: 表示这个点是否已经确定了最短路径!
int s, t;
//之所以开pair是因为我们的堆维护的是节点到源点的距离,自然就要知道节点编号!
typedef pair<int, int> PII;
void add (int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
int dj ()
{
memset (st, false, sizeof (st));
memset (dist, 0x3f, sizeof (dist));
priority_queue<PII, vector<PII>, greater<PII>> heap;
dist[s] = 0;
heap.push({0, s}); //距离,节点编号!
while (heap.size())
{
//取出小根堆的顶点,即堆中最小的点,代表到源点距离最近的且没有确定最短路的节点
auto t = heap.top();
heap.pop();
int ver = t.second;
//用它去更新所有与它相连接的邻接点!
if (st[ver]) continue;
st[ver] = true;
for (int i=h[ver]; ~i; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[ver] + w[i])
{
dist[j] = dist[ver] + w[i];
heap.push({dist[j], j});
}
}
}
if (dist[t] == 0x3f3f3f3f) return -1;
else return dist[t];
}
int main()
{
while (scanf ("%d%d", &n, &m) != EOF)
{
memset(h, -1, sizeof h);
while (m -- )
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
}
cin >> s >> t;
cout << dj() << endl;
}
return 0;
}