洛谷 P1339 [USACO09OCT]热浪Heat Wave(最短路_SPFA)

本文介绍了一道经典的SPFA算法题目,并详细展示了其代码实现过程。SPFA(Shortest Path Faster Algorithm)是一种用于求解单源最短路径问题的有效算法,特别适用于含有大量边的图。文中通过具体实例讲解了如何使用SPFA算法来找到从起点到终点的最短路径。

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

传送门


SPFA裸题,似乎没什么好说的…

Code:

#include<cstdio>
#include<cstdlib>
#include<cstring>

struct node{int x,y,c,next;}a[13010];
int n,m,st,ed,len=0;
int f[2510],first[2510],q[3010];
bool v[2510];

void ins(int x,int y,int c){len++;a[len].x=x;a[len].y=y;a[len].c=c;a[len].next=first[x];first[x]=len;}

void spfa()
{
    q[1]=st;f[st]=0;v[st]=true;
    int head=1,tail=2;
    while(head!=tail)
    {
        int x=q[head];
        for(int i=first[x];i;i=a[i].next)
        {
            int y=a[i].y;
            if(f[y]>f[x]+a[i].c)
            {
                f[y]=f[x]+a[i].c;
                if(!v[y])
                {
                    v[y]=true;
                    q[tail++]=y;
                    if(tail>n) tail=1;
                }
            }
        }
        v[x]=false;
        head++;
        if(head>n) head=1;
    }
}

int main()
{
    memset(first,0,sizeof(first));
    memset(f,63,sizeof(f));
    memset(v,false,sizeof(v));
    scanf("%d %d %d %d",&n,&m,&st,&ed);
    for(int i=1;i<=m;i++)
    {
        int x,y,c;
        scanf("%d %d %d",&x,&y,&c);
        ins(x,y,c);ins(y,x,c);
    }
    spfa();
    printf("%d",f[ed]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值