Bellman-Ford求最短路和负环
时间复杂度:\(O(nm)\)
bool Bellman_Ford()
{
memset(dist, 0x3f, sizeof dist);
for (int k = 1; k < n; k ++)
for (int ver = 1; ver <= n; ver ++)
for (int i = h[ver]; ~i; i = ne[i])
{
int to = e[i];
if (dist[to] > dist[ver] + w[i])
dist[to] = dist[ver] + w[i];
}
for (int ver = 1; ver <= n; ver ++)
for (int i = h[ver]; ~i; i = ne[i])
{
int to = e[i];
if (dist[to] > dist[ver] + w[i])
return false;
}
return true;
}
SPFA求最短路
时间复杂度:\(O(E \times V)\)
vector 存图
struct Edge
{
int u, w;
};
vector<Edge> g[N];
int dist[N], n, m;
bitset<N> vis;
int spfa()
{
queue<int> q;
memset(dist, 0x3f3f3f, sizeof dist);
dist[1] = 0, vis[1] = true;
q.push(1);
while (!q.empty())
{
int x = q.front(); q.pop();
vis[x] = false;
for (auto y : g[x])
{
int v = y.u, w = y.w;
if (dist[v] > dist[x] + w)
{
dist[v] = dist[x] + w;
if (!vis[v])
{
q.push(v); vis[v] = true;
}
}
}
}
if (dist[n] == INF) return -114514;
else return dist[n];
}
链式前向星
bool SPFA(int st)
{
memset(dist, 0x3f, sizeof dist), hh = 0, tt = -1;
dist[st] = 0, que[++ tt] = st, vis[st] = true;
while (hh <= tt)
{
int ver = que[hh ++];
vis[ver] = false;
for (int i = h[ver]; ~i; i = ne[i])
{
int to = e[i];
if (dist[to] > dist[ver] + w[i])
{
dist[to] = dist[ver] + w[i];
if (++ cnt[to] > n) return false;
if (!vis[to]) que[++ tt] = to, vis[to] = true;
}
}
}
return true;
}
标签:ver,int,Bellman,Ford,return,vis,dist,true,模板
From: https://www.cnblogs.com/ThySecret/p/18523438