const int N = 1e5 + 10;
struct SPFA {
int n, m;
int h[N], w[N], e[N], ne[N], idx; int dist[N]; bool st[N];
void init()
{
scanf("%d%d", &m, &n);
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);
}
}
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int spfa(int s, int end)
{
memset(dist, 0x3f, sizeof dist);
dist[s] = 0;
queue<int> q;
q.push(s);
st[s] = true;
while (q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
if (!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
return dist[end];
}
}spfa;
int main()
{
spfa.init();
int t=spfa.spfa(spfa.n, 1);
cout << t << endl;
}
SPFA模板
于 2022-08-05 12:15:05 首次发布
本文介绍了使用SPFA(Shortest Path Faster Algorithm)算法解决最短路径问题,通过C++实现的步骤,从初始化边和顶点信息,到添加边并构建图,最后演示了如何进行单源最短路径搜索。重点在于理解并应用广度优先搜索的改进版算法。
摘要由CSDN通过智能技术生成