求最短路:spfa

13 阅读1分钟

spfa用来求负权值的最短路问题。

思想是重要一个节点变小了,就把它放到队列里,然后让它到队头。取出队头,更新一下所有的边。因为t变小了,所以所有以t为起点的终点的边也会变小。

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int h[N], e[N], w[N], ne[N], idx;
int dist[N];
bool st[N];
int n, m;

void add(int a, int b, int c)
{
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx++;
}
int 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;
                }
            }
        }
    }
    return dist[n];
}


int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while (m--)
    {
        int a, b, c; cin >> a >> b >> c;
        add(a, b, c);
    }
    int t = spfa();
    if (t == 0x3f3f3f3f)cout << "impossible" << endl;
    else  cout << t << endl;
    return 0;
}