边类
存储边的起点与终点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;
}