建图spfa

学完了看了遍老师的代码回来就会了,感觉不错


#include<iostream>

#include<cstring>
using namespace std;
struct line
{
int to;
int w;
int next;


}edge[10000];
int g[100];
int n,h,t,ans;
int tot;
void add1(int a, int b, int c) //a是当前边的起点,b是当前边的终点,c是权值
{
tot++; //当前边数
edge[tot].to = b; //当前边的终点
edge[tot].w = c; //当前边的权值
edge[tot].next = g[a]; //当然边的下一条边为a点所指的边
g[a] = tot; //a点指向当前边
}
bool rejudge[100];
int distant[100];
int q[100];
void spfa(int a, int b)
{
memset(distant, 99999, sizeof(int) * 100);
for (int i = 1;i <= n;i++)
rejudge[i] = false;
h = 0;
t = 1;
q[t] = a;
distant[a] = 0;
while (h != t)
{
h = h%n + 1; //q[h]为当前要储存的点
int x = q[h]; //点出队
int temp = g[x]; //取出点所指向的第一条边
while (temp != 0)
{
if (distant[edge[temp].to] > distant[x] + edge[temp].w) //relax
{
distant[edge[temp].to] = distant[x] + edge[temp].w;
if (!rejudge[edge[temp].to]) //判重
{
t = t%n + 1; //入队
q[t] = edge[temp].to;
rejudge[edge[temp].to] = true;
}
}
temp = edge[temp].next; //遍历当前节点的下一条边
}
rejudge[x] = false; //确保入队

}

return distant[b]; //返回终点值

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值