图论
图的存储方法
四种单源最短路比较
1129. 热浪 - AcWing题库
SPAF模板题。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N =2510, M=6200*2+10;
int n, m, S, T;
int h[N], e[M], w[M], ne[M], idx;
int q[N], dist[N];// 循环队列,距离的队列。
bool st[N];// 判重数组。
void add(int a, int b, int c) // 添加一条边a->b,边权为c
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
void spfa() // 求S号点到T号点的最短路距离
{
memset(dist, 0x3f, sizeof dist); // 初始化距离
dist[S] = 0;// S 到S 的距离为0.
int hh = 0, tt = 1;// 初始化一个队列。
q[0 ] = S;
st[S] = true;
while (hh != tt)
{
int t = q[hh ++ ];
if (hh == N) hh = 0;
st[t] = false;// 出队就标记为0
for (int i = h[t]; i != -1; i = ne[i])// 枚举下所有临边
{
int j = e[i];
if (dist[j] > dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
if (!st[j]) // 如果队列中已存在j,则不需要将j重复插入
{
q[tt ++ ] = j;
if (tt == N) tt = 0;
st[j] = true;// 入队就标记为true。
}
}
}
}
}
int main()
{
cin>> n>> m>>S>>T;
memset(h, -1, sizeof h);
for (int i = 0; i < m; i ++ )
{
int a, b,c;
cin >> a>>b>>c;
add(a, b, c),add(b,a,c);
}
spfa();
cout << dist[T]<< endl;
return 0;
}