您的位置:首页 > 汽车 > 新车 > 最短路:spfa算法

最短路:spfa算法

2024/6/30 17:21:49 来源:https://blog.csdn.net/weixin_43790371/article/details/139627010  浏览:    关键词:最短路:spfa算法

最短路:spfa算法

    • 题目描述
    • 参考代码![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/3be484da34a84911a0a7dab3f1d84945.png)

题目描述

参考代码在这里插入图片描述

输入示例

3 3
1 2 5
2 3 -3
1 3 4

输出示例

2
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>using namespace std;const int N = 1e5 + 10;int n, m;
int h[N], e[N], ne[N], w[N], idx;
int dist[N];
bool st[N];void add(int a, int b, int c)
{e[idx] = b; ne[idx] = h[a]; w[idx] = c; h[a] = idx; idx++;
}int spfa()
{memset(dist, 0x3f, sizeof dist);dist[1] = 0;queue<int> q;q.push(1);st[1] = true;while (q.size()){auto 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;}}}}if (dist[n] == 0x3f3f3f3f) return -1;return dist[n];
}int main()
{scanf("%d%d", &n, &m);memset(h, -1, sizeof h);while (m -- ){int x, y, z;scanf("%d%d%d", &x, &y, &z);add(x, y, z);}int t = spfa();if (t == -1) printf("impossible\n");else printf("%d\n", t);return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com