Bellman-Ford的优先队列

104 篇文章 0 订阅

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

#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
*/

这里写图片描述

//  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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值