蓝桥杯 道路和航路(SPFA算法求最短路径)

本文通过一个蓝桥杯竞赛题目介绍了SPFA算法的应用,该算法用于寻找图中从起点到各点的最短路径。文章提供了完整的C++代码实现,并针对特定数据集进行了优化讨论。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//蓝桥杯 道路和航路  (SPFA算法求最短路径)
//超时的两组数据
#include<iostream>
#include<cstdio>
#include<string.h>
#include<queue>
using namespace std;
const int N=30000;
const int Inf=100000000;
struct node
{
    int to;
    int value;
    int next;
};
int head[N];
int vis[N];//
int dis[N]={0};//存取距离
int t,r,P,s;
node p[N*6];
void init()
{
    memset(head,-1,sizeof(head[0])*(t+2));
    memset(vis,0,sizeof(vis[0])*(t+2));
    int k=0;
    int a,b,c;
    for(int i=0;i<r;i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        p[k].to=b;
        p[k].value=c;
        p[k].next=head[a];
        head[a]=k++;
        p[k].to=a;
        p[k].value=c;
        p[k].next=head[b];
        head[b]=k++;
    }
    for(int i=0;i<P;i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        p[k].to=b;
        p[k].value=c;
        p[k].next=head[a];
        head[a]=k++;
    }
}
//============关键算法===================
bool relax(int pr,int to,int value)
{
    if(dis[to]>dis[pr]+value)
    {
        dis[to]=dis[pr]+value;
        return true;
    }
    return false;
}
int SPAF(int d)
{
    for(int i=0;i<=t;i++)
    {
        dis[i]=Inf;
    }
    vis[d]=1;
    dis[d]=0;
    queue<int> que;
    que.push(d);
    while(!que.empty())
    {
        int pre=que.front();
        que.pop();
        vis[pre]=0;
        for(int i=head[pre];i+1;i=p[i].next)
        {
            if(relax(pre,p[i].to,p[i].value)&&!vis[p[i].to])
            {
                que.push(p[i].to);
                vis[p[i].to]=1;
            }
        }
    }

}
//==========================================
int main()
{
    scanf("%d%d%d%d",&t,&r,&P,&s);
    init();
    SPAF(s);
    for(int i=1;i<=t;i++)
    {
        if(dis[i]==Inf)
        {
            printf("NO PATH\n");
        }
        else
        {
            printf("%d\n",dis[i]);
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

u014068781

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

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

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

打赏作者

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

抵扣说明:

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

余额充值