spfa算法,时间复杂度$O(m)$ spfa没死
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 2010, M = 200010;
int n, m;
int h[N], e[M], ne[M], w[N], targrt[M], idx;
int dist[N];
bool st[N];
queue<int> q;
void add(int a, int b, int c)
{
e[idx] = b, ne[idx] = h[a], targrt[idx] = c, h[a] = idx++;
}
void spfa()
{
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], k = targrt[i];
if (dist[k] > max(dist[t], dist[j]) + max(w[t], w[j]))
{
dist[k] = max(dist[t], dist[j]) + max(w[t], w[j]);
if (!st[k]) q.push(k), st[k] = true;
}
}
}
}
int main()
{
int k, T;
cin >> n >> k >> m >> T;
for (int i = 1; i <= n; ++i) scanf("%d", &w[i]);
memset(dist, 0x3f, sizeof dist);
while (k--)
{
int x;
scanf("%d", &x);
dist[x] = 0;
q.push(x);
st[x] = true;
}
memset(h, -1, sizeof h);
while (m--)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c), add(b, a, c);
}
spfa();
cout << dist[T] << endl;
return 0;
}
dijkstra算法,时间复杂度$O(n^2)$
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 2010, M = 200010;
int n, m;
int h[N], e[M], ne[M], w[N], targrt[M], idx;
int dist[N];
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b, ne[idx] = h[a], targrt[idx] = c, h[a] = idx++;
}
void dijkstra()
{
for (int i = 0; i < n - 1; ++i)
{
int t = 0;
for (int i = 1; i <= n; ++i)
if (!st[i] && dist[i] < dist[t])
t = i;
st[t] = true;
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i], k = targrt[i];
dist[k] = min(dist[k], max(dist[t], dist[j]) + max(w[t], w[j]));
}
}
}
int main()
{
int k, T;
cin >> n >> k >> m >> T;
for (int i = 1; i <= n; ++i) scanf("%d", &w[i]);
memset(dist, 0x3f, sizeof dist);
while (k--)
{
int x;
scanf("%d", &x);
dist[x] = 0;
}
memset(h, -1, sizeof h);
while (m--)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c), add(b, a, c);
}
dijkstra();
cout << dist[T] << endl;
return 0;
}