「AcWing学习记录」SPFA

发布时间 2023-03-22 22:43:18作者: 恺雯

image

AcWing 851. spfa求最短路

原题链接

queue \(\leftarrow\) 1
while queue不空
1.t \(\leftarrow\) q.front;
q.pop();
2.更新t的所有出边,t \(\to\) b
queue \(\leftarrow\) b

#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 1e6 + 10;

int n, m;
int h[N], w[N], e[N], ne[N], idx;
int dist[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[1] = 0;

    queue<int> q;
    q.push(1);
    st[1] = 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;
                }
            }
        }
    }
}

int main()
{
    cin >> n >> m;

    memset(h, -1, sizeof h);

    while (m -- )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }

    spfa();

    if(dist[n] == 0x3f3f3f3f) puts("impossible");
    else cout << dist[n] << endl;

    return 0;
}

AcWing 852. spfa判断负环

原题链接