SPFA算法模板

简介

SPFA 算法是 Bellman-Ford算法 的队列优化算法的别称,通常用于求含负权边的单源最短路径,以及判负权环。SPFA 最坏情况下时间复杂度和朴素 Bellman-Ford 相同,为 O(VE)。

代码

求最短路版(和dijkstra堆优化有点类似)
//spfa求最短路
#include <bits/stdc++.h>

using namespace std;

const int N = 100010;
int e[N], ne[N], h[N], w[N], idx;
int n, m, 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++;
}

int spfa()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;

    queue<int> qu;
    qu.push(1);
    st[1] = true;

    while (!qu.empty())
    {
        int t = qu.front();
        qu.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])
                {
                    st[j] = true;
                    qu.push(j);
                }
            }
        }
    }

    return dist[n];
}

int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for (int i = 1; i <= m; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }

    spfa();

    if (dist[n] == 0x3f3f3f3f)
        puts("impossible");
    else
        cout << dist[n] << endl;
    return 0;
}
判断负环版

我们需要注意的是加上判断负环的话,时间复杂度可能就会比较高

#include <bits/stdc++.h>

using namespace std;

const int N = 100010;
int e[N], ne[N], h[N], w[N], idx;
int n, m, dist[N], cnt[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++;
}

int spfa()
{
    queue<int> qu;
    for(int i = 1; i <= n; i++)//因为是判断图中是否存在负环,而不是看单一的点,故而在遍历的时候我们首先要把所有的点都放到队列中
    {
        st[i] = true;
        qu.push(i);
    }

    while (!qu.empty())
    {
        int t = qu.front();
        qu.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];
                cnt[j] = cnt[t] + 1;
                if(cnt[j] >= n) return true;//(抽屉原理,当cnt>=n时一定遍历了大于等于n+1个点,由抽屉原理可知一定重复遍历了一些点,那么就存在负环)
                if (!st[j])
                {
                    st[j] = true;
                    qu.push(j);
                }
            }
        }
    }

    return false;
}

int main()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for (int i = 1; i <= m; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }

    if (spfa())
        puts("Yes");
    else
        puts("No");
	
	return 0;
}
  • 13
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,这是一份 SPFA 算法模板: ``` #include<bits/stdc++.h> using namespace std; const int N=1e5+10; const int M=1e5+10; const int INF=0x3f3f3f3f; int head[N],tot,n,m,s,dis[N]; bool vis[N]; struct node{ int next,to,w; }e[M]; inline void add(int from,int to,int w){ e[++tot].to=to; e[tot].w=w; e[tot].next=head[from]; head[from]=tot; } inline void SPFA(int s){ queue<int> q; memset(dis,0x3f,sizeof dis); memset(vis,0,sizeof vis); dis[s]=0; vis[s]=1; q.push(s); while(!q.empty()){ int u=q.front(); q.pop(); vis[u]=0; for(int i=head[u];i;i=e[i].next){ int to=e[i].to; if(dis[to]>dis[u]+e[i].w){ dis[to]=dis[u]+e[i].w; if(!vis[to]){ q.push(to); vis[to]=1; } } } } } int main(){ cin>>n>>m>>s; for(int i=1;i<=m;i++){ int from,to,w; cin>>from>>to>>w; add(from,to,w); } SPFA(s); for(int i=1;i<=n;i++) cout<<dis[i]<<" "; return 0; } ``` 请注意,这份代码仅仅是一个模板,需要根据实际需求进行修改。 ### 回答2: SPFA(Shortest Path Faster Algorithm)是一种用于求解最短路径的算法,下面给出一个SPFA算法模板: ```python import queue # 定义图的节点类 class Node: def __init__(self, index): self.index = index self.next = None self.weight = None # SPFA算法函数 def spfa(start, end, graph): # 初始化距离数组和队列 dist = [float('inf')] * len(graph) dist[start] = 0 q = queue.Queue() q.put(start) # 利用队列进行广度优先搜索 while not q.empty(): u = q.get() node = graph[u] while node: v = node.index w = node.weight # 松弛操作 if dist[u] + w < dist[v]: dist[v] = dist[u] + w q.put(v) node = node.next # 返回最短路径长度 return dist[end] # 测试数据 if __name__ == "__main__": # 初始化图的邻接表 graph = [None] * 5 graph[0] = Node(1) graph[0].next = Node(2) graph[0].next.next = Node(4) graph[0].weight = 2 graph[0].next.weight = 4 graph[0].next.next.weight = 1 graph[1] = Node(2) graph[1].next = Node(3) graph[1].weight = 6 graph[1].next.weight = 3 graph[2] = Node(3) graph[2].weight = 2 graph[4] = Node(3) graph[4].weight = 3 start = 0 end = 3 result = spfa(start, end, graph) print("最短路径长度:", result) ``` 该模板中,首先定义了一个节点类表示图的节点,包含节点索引、指向的下一个节点和边的权重信息。 然后,实现了SPFA算法的函数`spfa`,其中利用队列实现广度优先搜索,对于每个节点,根据当前节点的距离更新相邻节点的距离值。 最后,在主函数中,根据测试数据初始化图的邻接表,并设定起点和终点,最后调用`spfa`函数求解最短路径长度并输出结果。 希望对你有帮助! ### 回答3: SPFA算法,即适用于求解单源最短路径的 Bellman-Ford 算法的一种优化算法,全称为 Shortest Path Faster Algorithm。下面是一个SPFA算法模板: ```python import collections def spfa(graph, start): # 初始化距离数组和队列 distance = [float('inf')] * len(graph) distance[start] = 0 queue = collections.deque([start]) in_queue = [False] * len(graph) in_queue[start] = True while queue: curr_node = queue.popleft() in_queue[curr_node] = False for neighbor, weight in graph[curr_node]: new_distance = distance[curr_node] + weight if new_distance < distance[neighbor]: distance[neighbor] = new_distance if not in_queue[neighbor]: queue.append(neighbor) in_queue[neighbor] = True return distance ``` 其中,`graph`为表示图的邻接表形式,包含了节点及其邻居节点及边的权重信息。`start`表示起始节点的索引。 算法运行开始时,将起始节点加入队列,并设置距离数组中起始节点的距离为0。进入循环,每次从队列中取出一个节点,并更新其连接节点的最短距离。如果发现某个节点的最短距离有更新,则将该节点加入队列中继续扩展,并将其标记为在队列中。 最后,返回得到的各个节点到起始节点的最短距离数组 `distance`。如果某个节点的最短距离为初始时设置的 `float('inf')`,则表示该节点不可到达。 这是一个简单的SPFA算法模板,适用于解决不含负权环的最短路径问题。需要注意的是,如果图中存在负权环,该算法将无法得到正确结果,因为它没有负权环的停止条件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值