poj3268

本文深入探讨了SPFA(Shortest Path Faster Algorithm)算法的基本原理及其C++实现过程,通过一个具体的示例展示了如何使用SPFA算法求解最短路径问题,并与Floyd算法进行了对比。

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

spfa。。。。其实最好用floyed,最简单,只是很久没写spfa了,练习一下

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cmath>

using namespace std;

int n , m , k , all;
const int M = 1e5;

int pre[M + 10] , other[M + 10] , last[M + 10] , cost[M + 10] , seq[M + 10];
int dis[M + 10] , Inque[M + 10];

void build(int x , int y , int z)
{
    pre[++all] = last[x];
    last[x] = all;
    other[all] = y;
    cost[all] = z;
}

int  spfa(int s , int x)
{
    memset(Inque , 0 , sizeof(Inque));
    int head , tail , now , ed , dr;
    head = 1 , tail = 0;
    seq[++tail] = s;
    for(int i = 1 ; i <= n ; i++) dis[i] = 1 << 30;
    dis[s] = 0;
    Inque[s] = 1;
    while(head <= tail){
        now = seq[head];
        ed = last[now];
        Inque[now] = 0;
        while(ed != -1){
            dr = other[ed];
            if(dis[now] + cost[ed] < dis[dr]){
                dis[dr] = dis[now] + cost[ed];
                if(!Inque[dr]){
                    Inque[dr] = 1;
                    seq[++tail] = dr;
                }
            }
            ed = pre[ed];
        }
        head++;
    }
    return dis[x];
}

int main()
{
    while(~scanf("%d %d %d",&n , &m , &k)){
        memset(last , -1 , sizeof(last));
        all = -1;
        for(int i = 1 ; i <= m ; i++){
            int a , b , c;
            scanf("%d %d %d",&a , &b , &c);
            build(a , b , c);
        }
        int ans = 0;
        for(int i = 1 ; i <= n ; i++){
            int tmp = 0;
            tmp += spfa(i,k);
            tmp += spfa(k,i);
            if(ans < tmp) ans = tmp;
        }
        printf("%d\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值