邻接表存储图的SPFA的C实现

边类

        存储边的起点与终点id。

struct ArcNode {
    ArcNode *nextarc;
    int a, b;
    int weight;
} * E;  //边

点类

        存储第一条边。

struct node {
    ArcNode *firstarc;
} * V;  //点

算法实现

#include <iostream>
using namespace std;
const int oo = 32767;

struct ArcNode {
    ArcNode *nextarc;
    int a, b;
    int weight;
} * E;  //边

struct node {
    ArcNode *firstarc;
} * V;  //点

int n, m;  //n为节点个数m为边的条数
int begin;
int *D;  //D[i]记录从原点到i的最短路径

int spfa() {
    int i;
    D = new int[n + 1];
    for (i = 1; i <= n; i++) {
        D[i] = oo;
    }
    D[begin] = 0;
    int front = 1, rear = 2;
    int *queue;
    queue = new int[2 * n + 1];  //队列
    queue[1] = begin;
    ArcNode *p;
    while (front != rear) {
        p = V[queue[front++]].firstarc;
        while (p != NULL) {
            if (D[p->b] >= D[p->a] + p->weight) {
                D[p->b] = D[p->a] + p->weight;
                queue[rear++] = p->b;
            }                //不断松弛
            p = p->nextarc;  //下一条边
        }
    }
    return 0;
}

int main() {
    int i;
    int a, b, w;
    ArcNode *p;
    cin >> n >> m;
    cin >> begin;
    V = new node[n + 1];
    E = new ArcNode[m + 1];
    for (i = 1; i <= n; i++) {
        V[i].firstarc = NULL;
    }
    for (i = 1; i <= m; i++) {
        cin >> a >> b >> w;
        E[i].a = a;
        E[i].b = b;
        E[i].weight = w;
        E[i].nextarc = NULL;
        p = V[a].firstarc;
        if (p == NULL) {
            V[a].firstarc = &E[i];
        } else {
            while (p->nextarc != NULL) {
                p = p->nextarc;
            }
            p->nextarc = &E[i];
        }  //插入边节点
    }
    spfa();
    for (i = 1; i <= n; i++) {
        cout << D[i] << ' ';
    }
    cout << endl;
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值