题目描述
给定 $n$ 个 点 和 $m$ 条 边
起点 编号为 $1$
求从起点出发,抵达所有点的 最短距离的最大值
分析
也是一道 ” 单源最短路 “问题
点数为 $100$,边数为 $200$,朴素版 和 堆优化版 的 Dijkstra 都可
朴素版 Dijkstra 的运算上界为 $10000$
对优化办 Dijkstra 的运算上界为 $1992$
Code(朴素版)
时间复杂度: $O(n^2)$
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 110;
int n, m;
int g[N][N];
int dist[N];
bool st[N];
int dijkstra()
{
int res = 0;
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
for (int i = 1; i <= n; 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;
res = max(res, dist[t]);
for (int j = 1; j <= n; j ++ )
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
return res == 0x3f3f3f3f ? -1 : res;
}
int main()
{
memset(g, 0x3f, sizeof g);
scanf("%d%d", &n, &m);
while (m -- )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
g[a][b] = g[b][a] = min(g[a][b], c);
}
cout << dijkstra() << endl;
return 0;
}
Code(堆优化版)
时间复杂度: $O(m\log n)$
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 110, M = N << 2;
int n, m;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
int dijkstra()
{
int res = 0, cnt = 0;
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
priority_queue<PII, vector<PII>, greater<>> heap;
heap.push({0, 1});
while (!heap.empty())
{
PII u = heap.top();
heap.pop();
if (st[u.y]) continue;
st[u.y] = true;
res = max(res, u.x);
cnt ++ ;
for (int i = h[u.y]; ~i; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[u.y] + w[i])
{
dist[j] = dist[u.y] + w[i];
heap.push({dist[j], j});
}
}
}
return cnt == n ? res : -1;
}
int main()
{
memset(h, -1, sizeof h);
scanf("%d%d", &n, &m);
while (m -- )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c), add(b, a, c);
}
cout << dijkstra() << endl;
return 0;
}
👍
堆优化版打错了吧hh
好像是可以ac的
那是我见识少了hh