SPFA(链式前向星)

SPFA

与djkstra比可判断负环,处理负权边

//SPFA
#include<bits/stdc++.h>
using namespace std;
const int maxn = 10100;         //最大顶点数
const int maxm = 500500;        //最大边数
const int inf = 0x3f3f3f3f;     //inf无限大
struct edge{                    //链式前向星建图
    int to,next,w;
}e[maxm];
int using_v[maxn],using_times[maxn];//入队的点和点的入队次数
int head[maxn],dis[maxn];
int cnt=0;
int n,m;        //n个点m条边
void addedge(int u,int v,int w){
    e[++cnt].to = v;
    e[cnt].w = w;
    e[cnt].next = head[u];
    head[u] = cnt;
}
int spfa(int start){
    queue<int>q;
    dis[start] = 0;         //起始点离自己的dis为0
    using_v[start] = 1;     //起始点标记
    q.push(start);          //入队
    while(!q.empty()){//fs
        int top=q.front();  //队首
        q.pop();            //取出
        using_v[top] = 0;   //top这个点暂时没在队列中
        using_times[top]++; //使用次数++
        if(using_times[top]>n) return 0;        //存在复环
        for(int i = head[top];i;i=e[i].next){   //图遍历
            if(dis[e[i].to]>dis[top]+e[i].w){   //松弛
                dis[e[i].to] = dis[top]+e[i].w;
                if(!using_v[e[i].to]){
                    using_v[e[i].to] = 1;       //入队
                    q.push(e[i].to);
                }
            }
        }
    }
    return 1;
}
int main()
{
    int u,v,w,s;    //u--->v的权值为w,s为起始点
    cin >> n >> m >> s;
    memset(dis,inf,sizeof(dis));
    for(int i = 0;i < m;i++){
        cin >> u >> v >> w;
        addedge(u,v,w);
    }
    spfa(s);
    for(int i = 1;i <= n;i++){
        if(dis[i] != inf)
            cout << dis[i] << " ";
        else
            cout << "inf" << " ";
    }

    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值