Bellman-Ford的优先队列

参考啊哈算法第六章第四节

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <math.h>
using namespace std;

const int inf=999999;
int book[6];//记录哪些点已经在队列中。
int que[101];

int main()
{
    int n,m;
    int u[8],v[8],w[8];
    int first[6],next[8];
    int dis[6];
    int head=1,tail=1;
    scanf("%d%d",&n,&m);
    dis[1]=0;
    for(int i=2;i<=n;i++)
        dis[i]=inf;
    for(int i=1;i<=n;i++)
        first[i]=-1;
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&u[i],&v[i],&w[i]);
        next[i]=first[u[i]];
        first[u[i]]=i;
    }
    que[tail]=1;
    tail++;
    book[1]=1;
    while(head<tail)
    {
        int k=first[que[head]];
        while(k!=-1)
        {
            if(dis[v[k]]>dis[u[k]]+w[k])
            {
                dis[v[k]]=dis[u[k]]+w[k];
                if(book[v[k]]==0)
                {
                    que[tail]=v[k];
                    tail++;
                    book[v[k]]=1;
                }
            }
            k=next[k];
        }
        book[que[head]]=0;
        head++;
    }
    for(int i=1;i<=n;i++)
        printf("%4d",dis[i]);
    return 0;
}
/* 5 7 1 2 2 1 5 10 2 3 3 2 5 7 3 4 4 4 5 5 5 3 6 */

《Bellman-Ford的优先队列》

// 1---n 最短路
#include<bits/stdc++.h>

using namespace std;

#define inf 0x3f3f3f3f
#define mm(a,b) memset(a,b,sizeof(a))

const int N=1e2+10;

struct node{
    int to,w,next;
};

node g[100*N];
int dis[N];
bool vis[N];
int head[N];
int n,m,len;

inline void addedge(int u,int v,int w){
    g[len].to=v;
    g[len].w=w;
    g[len].next=head[u];
    head[u]=len++;
}

void spfa(int u){
    mm(vis,0);
    mm(dis,inf);
    queue<int> q;
    q.push(u);
    dis[u]=0;vis[u]=1;
    while(!q.empty()){
        u=q.front();q.pop();
        vis[u]=0;
        for(int i=head[u];~i;i=g[i].next){
            int to=g[i].to,w=g[i].w;
            if(dis[to]>dis[u]+w){
                dis[to]=dis[u]+w;
                if(!vis[to]){
                    q.push(to);
                    vis[to]=1;
                }
            }
        }
    }
}

int main(){
    int u,v,w;
    while(scanf("%d%d",&n,&m)&&(n||m)){
        len=0;
        mm(head,-1);
        for(int i=0;i<m;i++){
            scanf("%d%d%d",&u,&v,&w);
            addedge(u,v,w);
            addedge(v,u,w);
        }
        spfa(1);
        printf("%d\n",dis[n]);
    }
    return 0;
}
    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/qq_40679299/article/details/79393258
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞