一个我认为比较好的Spfa模板(使用邻接表和队列实现)

本文详细介绍了使用邻接表和队列实现的SPFA(Shortest Path Faster Algorithm)模板,包括全局变量的初始化、邻接表结构、添加边的函数以及SPFA核心算法的实现过程。通过SPFA可以找到图中从源点到各个点的最短路径,区别于Dijkstra算法,SPFA维护的是一个包含源节点的队列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

全局准备工作
int N, X;	//N为点数 X为源点
int head[MAXN];	//head[src]表示以head为出发点的邻接表表头在数组Adj中的位置,开始时所有元素初始化为-1
int nodeP;	//在邻接表和指向表头的head数组中定位用的记录指针,开始时初始化为0
int dist[MAXN];	//储存到源节点的距离,在Spfa()中初始化
bool vis[MAXN];	//这里vis作inqueue解释会更好,出于习惯使用了vis来命名,在Spfa()中初始化
 Node定义 
struct Node {
    int v, w, next;
}Adj[MAXM];
v即vertex,这里意思相当于被指向的点to,w相当于weight,代表边权,next用来指向在Adj中下一个从相同src出发的边指向的点
 
 addEdge函数 
void addEdge(int src, int to, int weight)
{
    Adj[nodeP].v = to;
    Adj[nodeP].w = weight;
    Adj[nodeP].next = head[src];
    head[src] = nodeP++;
}
addEdge(a, b, w)作用是在数组Adj中留下一条记录了去向和边权的记录,且其next指向表中相同src指向的下一个点,同时更新了head表头
 
 Spfa主体 
void Spfa()
{
    queue<int> que;
    int i;
    for(i = 1; i <= N; i++) {
        dist[i] = NIL;
        vis[i] = false;
    }
  
### 回答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算法模板,适用于解决不含负权环的最短路径问题。需要注意的是,如果图中存在负权环,该算法将无法得到正确结果,因为它没有负权环的停止条件。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值