# [Luogu 3371] [template] single source shortest path (spfa+slf)

Problem description
For example, if a directed graph is given, please output the shortest path length from a point to all points.
input
The first line contains three integers N, M and S, which respectively represent the number of points, the number of directed edges and the number of starting points.
Next, each row of row M contains three integers Fi, Gi and Wi, which respectively represent the starting point, target point and length of the i-th directed edge.
output
One line, containing N integers separated by spaces, where the i-th integer represents the shortest path length from point S to point I (if S=i, the shortest path length is 0; if from point S cannot reach point I, the shortest path length is 2147483647)
sample input
4 6 1
1 2 2
2 3 2
2 4 1
1 3 5
3 4 3
1 4 4
sample output
0 2 4 3
Algorithm discussion
spfa template. Plus an slf optimization, if the current point is j, the team head is i, if d[j]

```#include <cstdio>
#include <deque>
using namespace std;
#define maxn 10006
#define maxm 500006
#define maxlongint 2147483647
struct edge
{
int f,t,w,n;
}a[maxm];
deque <int> q;
int d[maxn],ls[maxn],n,m,s;
bool v[maxn];

int init()
{
scanf("%d%d%d",&n,&m,&s);
for (int i=1;i<=m;i++)
{
scanf("%d%d%d",&a[i].f,&a[i].t,&a[i].w);
a[i].n=ls[a[i].f];
ls[a[i].f]=i;
}
return 0;
}

int spfa()
{
for (int i=1;i<=n;i++)
d[i]=maxlongint;
d[s]=0; v[s]=1;
q.push_back(s);
while (!q.empty())
{
int u=q.front();
q.pop_front(); v[u]=0;
for (int i=ls[u];i;i=a[i].n)
if (d[u]+a[i].w<d[a[i].t])
{
d[a[i].t]=d[u]+a[i].w;
if (!v[a[i].t])
{
v[a[i].t]=1;
if (q.empty() || d[a[i].t]>d[q.front()])
q.push_back(a[i].t);
else
q.push_front(a[i].t);
}
}
}
for (int i=1;i<=n;i++)
printf("%d ",d[i]);
return 0;
}

int main()
{
init();
spfa();
return 0;
}``` Pixiv ID:63134378

Posted on Sun, 03 May 2020 22:17:18 -0400 by Xasho