链式前向星版spfa最短路

spfa与dijkstra和Bellman-Frod一样都可以用来做最短路径问题,但是dijkstra没法判断负环,而Bellman-Frod虽然能检测负环但是效率太低。所以这个时候我们不得不借助于spfa。spfa为什么能操作负环呢?其实dijkstra和spfa的工作原理差不多,dijkstra是一个优先队列,只选取当前最小的,没考虑到后面负权值对后面的影响;而spfa是一个普通的队列,他只会来回筛选,直到队列为空,所以可以考虑到所有的情况,但是效率比dijkstra低一点。代码如下:


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#define inf 0x3f3f3f3f
 
using namespace std;
 
const int maxn = 1005;
 
int n, m, s, t;   //n为点数 s为源点
int head[maxn]; //head[from]表示以head为出发点的邻接表表头在数组es中的位置,开始时所有元素初始化为-1
int d[maxn]; //储存到源节点的距离,在Spfa()中初始化
int cnt[maxn];
bool inq[maxn]; //这里inq作inqueue解释会更好,出于习惯使用了inq来命名,在Spfa()中初始化
int nodep;  //在邻接表和指向表头的head数组中定位用的记录指针,开始时初始化为0
int pre[maxn];
 
struct node {
    int v, w, next;
}es[maxn * maxn * 2];
 
void init() {
    for(int i = 1; i <= n; i++) {
        d[i] = inf;
        inq[i] = false;
        cnt[i] = 0;
        head[i] = -1;
        pre[i] = -1;
    }
    nodep = 0;
}
 
void addedge(int from, int to, int weight)
{
    es[nodep].v = to;
    es[nodep].w = weight;
    es[nodep].next = head[from];
    head[from] = nodep++;
}
 
bool spfa()
{
    queue<int> que;
    d[s] = 0;    //s为源点
    inq[s] = 1;
    que.push(s);
    while(!que.empty()) {
        int u = que.front();
        que.pop();
        inq[u] = false;   //从queue中退出
        //遍历邻接表
        for(int i = head[u]; i != -1; i = es[i].next) {  //在es中,相同from出发指向的顶点为从head[from]开始的一项,逐项使用next寻找下去,直到找到第一个被输
                                                        //入的项,其next值为-1
            int v = es[i].v;
            if(d[v] > d[u] + es[i].w) { //松弛(RELAX)操作
                d[v] = d[u] + es[i].w;
                pre[v] = u;
                if(!inq[v]) {      //若被搜索到的节点不在队列que中,则把to加入到队列中去
                    inq[v] = true;
                    que.push(v);
                    if(++cnt[v] > n) {
                        return false;
                    }
                }
            }
        }
    }
    return true;
}
 
void putpath() {
    stack<int> path;
    int now = t;
    while(1) {
        path.push(now);
        if(now == s) {
            break;
        }
        now = pre[now];
    }
    while(!path.empty()) {
        now = path.top();
        path.pop();
        printf("%d\n", now);
    }
}
 
int main()
{
    while(cin >> m >> n) {
        init();
        int a, b, c;
        while(m--) {
            cin >> a >> b >> c;
            addedge(a, b, c);
            addedge(b, a, c);
        }
        s = n, t = 1;
        if(spfa()) {
            cout << d[t] << endl;
        }//putpath();
    }
    return 0;
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SPFA算法(Shortest Path Faster Algorithm)是一种用于解决最短路问题的算法。它是一种单源最短路径算法,可以解决带有负权边的图的最短路径问题。 SPFA算法基本思想是使用队列对图中的所有节点进行遍历,对于每一个节点,如果它的邻居节点的最短路径可以通过当前节点更新,则将邻居节点加入队列中进行下一轮遍历,直到所有节点的最短路径都被更新后停止遍历。 在Java中,可以使用邻接矩阵或邻接表来表示图,并使用队列来实现SPFA算法。下面是一个使用邻接矩阵实现SPFA算法的Java代码示例: ```java import java.util.*; public class SPFA { public static void main(String[] args) { int[][] graph = { {0, 2, 5, Integer.MAX_VALUE, Integer.MAX_VALUE}, {Integer.MAX_VALUE, 0, 7, 1, Integer.MAX_VALUE}, {Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 4, Integer.MAX_VALUE}, {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 3}, {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 0} }; int[] dist = shortestPath(graph, 0); System.out.println(Arrays.toString(dist)); } public static int[] shortestPath(int[][] graph, int start) { int n = graph.length; int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); dist[start] = 0; Queue<Integer> queue = new LinkedList<>(); queue.offer(start); boolean[] inQueue = new boolean[n]; inQueue[start] = true; while (!queue.isEmpty()) { int u = queue.poll(); inQueue[u] = false; for (int v = 0; v < n; v++) { if (graph[u][v] != Integer.MAX_VALUE && dist[v] > dist[u] + graph[u][v]) { dist[v] = dist[u] + graph[u][v]; if (!inQueue[v]) { queue.offer(v); inQueue[v] = true; } } } } return dist; } } ``` 在上面的代码中,我们使用一个二维数组`graph`来表示图,其中`graph[i][j]`表示从节点`i`到节点`j`的边的权重,如果没有边则为`Integer.MAX_VALUE`。函数`shortestPath`接受一个图和一个起点`start`,返回一个数组`dist`,其中`dist[i]`表示从起点`start`到节点`i`的最短路径。 在函数中,我们首先初始化`dist`数组为`Integer.MAX_VALUE`,表示所有节点到起点的距离都是无限大。然后将起点`start`加入队列中,并标记为已加入队列。进入循环后,每次取出队列中的一个节点`u`,将`u`标记为未加入队列,然后遍历`u`的所有邻居节点`v`,如果从起点到`v`的距离可以通过从起点到`u`再加上`u`到`v`的距离来更新,则更新`dist[v]`的值,并将`v`加入队列中,并标记为已加入队列。当队列为空时,所有节点的最短路径都已被更新,函数返回`dist`数组。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值