【最短路】【模板】Bellman-Ford 队列优化/spfa

/*Bellman-Ford*/
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;

const int M=500005;
const int INF=2000000000;
class node
{
public:
    int v,next,w;
} edge[M];
int ei;
int head[M];
int n;
int dis[M];
void addedge(int u,int v,int w)
{
    edge[++ei].v=v,edge[ei].w=w;
    edge[ei].next=head[u];
    head[u]=ei;
}

void Bellman_Ford(int x)
{
    queue<int>q;
    bool inthequeue[M]= {0};
    for(int i=1; i<=n; i++)
        dis[i]=INF;
    dis[1]=0;
    q.push(1);
    while(!q.empty())
    {
        int i=q.front();
        for(int j=head[i]; j!=-1; j=edge[j].next)
        {
            node &e=edge[j];
            if(dis[e.v]>dis[i]+e.w)
            {
                dis[e.v]=dis[i]+e.w;
                if(inthequeue[e.v]==0)
                {
                    q.push(e.v);
                    inthequeue[e.v]=1;
                }
            }

        }
        q.pop();inthequeue[i]=0;
    }
}

int main()
{
    memset(head,-1,sizeof(head));
    scanf("%d",&n);
    int m;
    scanf("%d",&m);
    for(int i=0; i<m; i++)
    {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        addedge(u,v,w);
    }
    Bellman_Ford(1);
    for(int i=1; i<=n; i++)
        printf("%d ",dis[i]);
}

 

    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/qq_32259423/article/details/81356839
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞