SPFA算法 Bellman_ford优化

#include<bits/stdc++.h>
#define INF 100000000
#define Maxn 50002
using namespace std;
struct node
{
    int to;
    int weight;
    node *next;
};
queue<int>Q;
int n;
node *List[Maxn];
int inq[Maxn];
int dis[Maxn],path[Maxn];
int SPFA(int sta)
{
    int i,u;
    node *temp;
    for(i=0; i<n; i++)
    {
        dis[i]=INF;
        path[i]=sta;
        inq[i]=0;
    }
    dis[sta]=0;
    path[sta]=sta;
    inq[sta]++;
    Q.push(sta);
    while(!Q.empty())
    {
        u=Q.front();
        Q.pop();
        inq[u]--;
        temp=List[u];
        while(temp!=NULL)
        {
            int v=temp->to;
            if(dis[v]>dis[u]+temp->weight)
            {
                dis[v]=dis[u]+temp->weight;
                path[v]=u;
                if(!inq[v])
                {
                    Q.push(v);
                    inq[v]++;
                }
            }
        teamp=temp->next; 
         }
    }
}
int main()
{
    int i,j;
    int u,v,w;
    scanf("%d",&n);
    memset(List,0,sizeof(List));
    node *temp;
    while(1)
    {
        scanf("%d%d%d",&u,&v,&w);
        if(u==-1&&v==-1&&w==-1)
            break;
        temp=new node;
        temp->to=v;
        temp->weight=w;
        temp->next=NULL;
        if(List[u]==NULL)
            List[u]=temp;
        else
        {
            temp->next=List[u];
            List[u]=temp;
        }
    }
    SPFA(0);
    int shortest[Maxn];
    for(i=1; i<n; i++)
    {
        printf("%d\t",dis[i]);
        memset(shortest,0,sizeof(shortest));
        int k=0;
        shortest[k]=i;
        while(path[shortest[k]]!=0)
        {
            k++;
            shortest[k]=path[shortest[k-1]];
        }
        k++;
        shortest[k]=0;
        for(j=k; j>0; j--)
            printf("%d ",shortest[j]);
        printf("%d\n",shortest[0]);
    }
    return 0;
}

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