### #1093 : 最短路径·三：SPFA算法

#### 输出

• 样例输入

• ```5 10 3 5
1 2 997
2 3 505
3 4 118
4 5 54
3 5 480
3 4 796
5 2 794
2 5 146
5 4 604
2 5 63```
• 样例输出

• `172`

AC代码：

#include<iostream>

#include<cstdio>

#include<cstdlib>

#include<string>

#include<algorithm>

#include<vector>

#include<stack>

#include<queue>

#include<deque>

#include<list>

#include<iterator>

using namespace std;

#define MAX 1000

#define INF 0x7fffffff

struct edge {

int to, weight;

};

struct Map {

bool in_queue[MAX];

int in_sum[MAX];

int dist[MAX];

int path[MAX];

int nodesum;

int edgesum;

};

Map mp;

bool SPFA(int sourse)

{

deque<int> dq;

int i, j, from, to;

for (i = 1; i <= mp.nodesum; i++)

{

mp.in_sum[i] = 0;

mp.in_queue[i] = false;

mp.dist[i] = INF;

mp.path[i] = -1;

}

dq.push_back(sourse);

mp.in_sum[sourse]++;

mp.dist[sourse] = 0;

mp.in_queue[sourse] = true;

while (!dq.empty()) {

from = dq.front();

dq.pop_front();

mp.in_queue[from] = false;

for (i = 0; i < mp.adjmap[from].size(); i++)

{

if ((mp.dist[from]<INF) && (mp.dist[to]>mp.dist[from] + mp.adjmap[from][i].weight))

{

mp.path[to] = from;

if (!mp.in_queue[to]) {

mp.in_queue[to] = true;

mp.in_sum[to]++;

if (mp.in_sum[to] == mp.nodesum)

return false;

if (!dq.empty())

{

if (mp.dist[to] > mp.dist[dq.front()])

dq.push_back(to);

else

dq.push_front(to);

}

else

dq.push_back(to);

}

}

}

}

return true;

}

int Get_SPFA(int goal)

{

return mp.dist[goal];

}

int main()

{

int i,start,sourse, goal;

edge temp;

int f;

while (scanf_s("%d %d %d %d", &mp.nodesum, &mp.edgesum, &sourse, &goal) != EOF) {

for (i = 1; i <= mp.nodesum; i++)

for (i = 1; i <= mp.edgesum; i++)

{

scanf_s("%d %d %d", &start, &temp.to, &temp.weight);

f = temp.to;

temp.to = start;

start = f;

}

if (SPFA(sourse))

{

printf("%d\n", Get_SPFA(goal));

}

}

return 0;

}