current position:Home>SPFA Template

SPFA Template

2022-08-06 08:55:05ThXe

const int N = 1e5 + 10;
struct SPFA {
    
  
    int n, m;
    int h[N], w[N], e[N], ne[N], idx;  int dist[N]; bool st[N];
    void init()
    {
    
        scanf("%d%d", &m, &n);
        memset(h, -1, sizeof h);
        while (m--)
        {
    
            int a, b, c;
            scanf("%d%d%d", &a, &b, &c);
            add(a, b, c);
            add(b, a, c);
        }
    }
    void add(int a, int b, int c)
    {
    
        e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
    }
    int spfa(int s, int end)
    {
    
        memset(dist, 0x3f, sizeof dist);
        dist[s] = 0;
        queue<int> q;
        q.push(s);
        st[s] = true;
        while (q.size())
        {
    
            int t = q.front();
            q.pop();
            st[t] = false;
            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])
                    {
    
                        q.push(j);
                        st[j] = true;
                    }
                }
            }
        }
        return dist[end];
    }
}spfa;
int main()
{
    
    spfa.init();
    int t=spfa.spfa(spfa.n, 1);
    cout << t << endl;
}

copyright notice
author[ThXe],Please bring the original link to reprint, thank you.
https://en.chowdera.com/2022/218/202208060847341998.html

Random recommended