AcWing 1129. 热浪(单源最短路)

题目链接

https://www.acwing.com/problem/content/1131/icon-default.png?t=N7T8https://www.acwing.com/problem/content/1131/

题解

此题属于单源最短路问题,根据数据范围,可以使用Dijkstra算法、堆优化版的Dijkstra算法、SPFA算法。本例采用SPFA算法,使用手写循环队列来实现。

代码

#include 
#include 
#include 

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 dist[N], q[N];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}

void spfa()
{
    memset(dist, 0x3f, sizeof dist);
    dist[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;
        
        for (int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > dist[t] + w[i])
            {
                dist[j] = dist[t] + w[i];
                if (!st[j])
                {
                    q[tt++] = j;
                    if (tt == N) tt = 0;
                    st[j] = 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;
}

参考资料

  1. AcWing算法提高课

你可能感兴趣的:(图论,最短路问题,图论,SPFA算法,Dijkstra算法,图)