旧代码 - 最短路 Spfa(邻接表)

本文介绍了一种名为 SPFA (Shortest Path Faster Algorithm) 的最短路径算法实现方式,该算法通过邻接表存储图结构,并使用队列进行节点间的遍历,能够有效地求解带负权边的最短路径问题。文中提供了完整的 C++ 实现代码及测试样例。

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

/*
PROG:   spfa_adjacent table
ID  :   ouyangyewei
LANG:   C++
*/
#include <queue>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define onlinejudge

const int maxn = 1004;
const int INF = 0x3F3F3F3F;

bool inq[maxn];
int  N, M, destination, dist[maxn], path[maxn];
struct ArcNode
{
    int v, w;
    ArcNode *next;
}*List[maxn];

void spfa(int src)
{
    int i, u;
    ArcNode *temp;
    queue <int> q;
    
    for (i=0; i<N; ++i)
        path[i]=-1, dist[i]=INF, inq[i]=false;
    
    dist[src]=0, inq[src]=true;
    q.push(src);
    while (!q.empty())
    {
        u = q.front();
        q.pop();
        inq[u] = false;
        
        temp = List[u];
        while (temp != NULL)
        {
            if (dist[u]+temp->w < dist[temp->v])
            {
                path[temp->v] = u;
                dist[temp->v] = dist[u]+temp->w;
                if (!inq[temp->v])
                    q.push(temp->v), inq[temp->v]=true;
            }
            
            temp = temp->next;
        }// end of while
    }// end of while
}// spfa

void dfs(int src, int xx)
{
    if (xx != src)
        dfs(src, path[xx]);
    
    if (xx != destination)
        printf("%d-->", xx);
    
    return ;
}// dfs

int main()
{
#ifdef onlinejudge
    freopen("E:\\bellman.txt", "r", stdin);
    freopen("E:\\bellman_ans.txt", "w", stdout);
#endif

    int i, a, b, c;
    while (~scanf("%d %d", &N, &M), N+M!=0)
    {
        memset(List, 0, sizeof(List));
        
        ArcNode *temp;
        for (i=0; i<M; ++i)
        {
            scanf("%d %d %d", &a, &b, &c);
            
            temp = new ArcNode;
            temp->v=b, temp->w=c, temp->next=NULL;
            if (List[a] == NULL)
                List[a] = temp;
            else
                temp->next=List[a], List[a]=temp;
        }// creat the adjacent table
        
        spfa( 0 );
        for (i=1; i<N; ++i)
        {
            printf("%d     ", dist[i]);
            destination = i;
            dfs(0, destination);
            printf("%d\n", i);
        }// end of for
    }// end of while
    
    return 0;
}
/*
Test:
    
7 10
0 1 6
0 2 5
0 3 5
1 4 -1
2 1 -2
2 4 1
3 2 -2
3 5 -1
4 6 3
5 6 3

0 0

Result:
  
1     0-->3-->2-->1
3     0-->3-->2
5     0-->3
0     0-->3-->2-->1-->4
4     0-->3-->5
3     0-->3-->2-->1-->4-->6  
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值