最短路问题——spfa算法

spfa算法是对bellman-ford算法的优化。
bellman-ford算法更新时有些更新是无效的,就造成了时间上的浪费,因此,spfa就用一个队列存储更新了的点,用更新的点更新后边的点。
就是说,只有前边一个点变小了,后边的点才可能变小。
操作步骤:

  • 1节点入队
  • 从队头取出一个元素,用该元素更新后边的结点,如果后边的节点是有效更新,就入队,重复这个操作。

spfa求最短路

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int h[N],e[N],ne[N],w[N],idx;
int dis[N];
bool st[N];
int n,m;

void Insert(int a,int b,int c){
    e[idx] = b;
    ne[idx] = h[a];
    w[idx] = c;
    h[a] = idx++;
}
int spfa(){
    memset(dis,0x3f,sizeof(dis));
    dis[1] = 0;
    st[1] = true;
    queue<int>q;
    q.push(1);
    while(q.size()){
        int t = q.front();
        q.pop();
        st[t] = false;//出队了就置为false
        for(int i=h[t];i!=-1;i=ne[i]){
            int j = e[i];
            if(dis[j]>dis[t]+w[i]){//只有这种情况才进行更新
                dis[j] = dis[t]+w[i];
                if(!st[j]){
                    q.push(j);
                    st[j] = true;
                }
            }
        }
    }
    if(dis[n]>0x3f3f3f3f/2)return -1;
    else return dis[n];
}

int main()
{
    memset(h,-1,sizeof(h));
    scanf("%d%d",&n,&m);
    int a,b,c;
    while(m--){
        scanf("%d%d%d",&a,&b,&c);
        Insert(a,b,c);
    }
    int res = spfa();
    if(res==-1)printf("impossible");
    else printf("%d",res);
    return 0;
}

spfa判负环

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int h[N],e[N],ne[N],w[N],idx;
int cnt[N],dis[N];
bool st[N];
int n,m;

void Insert(int a,int b,int c){
    e[idx] = b;
    ne[idx] = h[a];
    w[idx] = c;
    h[a] = idx++;
}

bool spfa(){
    queue<int>q;
    //判断负环,但不一定是从1出发的负环,所以把所有点都放进去。
    for(int i=1;i<=n;i++)q.push(i),st[i] = true;
    while(q.size()){
        int t = q.front();
        q.pop();
        st[t] = false;
        for(int i=h[t];i!=-1;i=ne[i]){
            int j = e[i];
            if(dis[j]>dis[t]+w[i]){
                dis[j] = dis[t]+w[i];
                cnt[j] = cnt[t]+1;
                if(cnt[j]>=n)return true;
                if(!st[j]){
                    st[j] = true;
                    q.push(j);
                }
            }
        }
    }
    return false;
}

int main()
{
    memset(h,-1,sizeof(h));
    scanf("%d%d",&n,&m);
    while(m--){
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        Insert(a,b,c);
    }
    if(spfa())printf("Yes\n");
    else printf("No\n");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

up-to-star

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值