SPFA的队列优化模板

版权声明:此博客为博主原创文章,未经博主同意请勿转载。 https://blog.csdn.net/major_zhang/article/details/79961007
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<set>
#include<queue>
using namespace std;
#define INF 0x3f3f3f3f
#define M(a, b) memset(a, b, sizeof(a))
const int maxn = 1000 + 5;

struct Edge {
    int from, to, dist;
};

struct SPFA {
    int d[maxn], cnt[maxn], p[maxn];
    int n, m;
    bool inq[maxn];
    vector<int> G[maxn];
    vector<Edge> edges;

    void init(int n) {
        this->n = n;
        for (int i = 1; i <= n; ++i) G[i].clear();
        edges.clear();
    }

    void AddEdge(int from, int to, int dist) {
        edges.push_back(Edge{from, to, dist});
        int m = edges.size();
        G[from].push_back(m-1);
    }

    bool spfa(int s) {
        M(d, INF); M(cnt, 0); M(inq, 0);
        d[s] = 0;
        queue<int> q;
        q.push(s);
        inq[s] = true;
        while (!q.empty()) {
            int u = q.front(); q.pop();
            inq[u] = false;
            for (int i = 0; i < G[u].size(); ++i) {
                Edge &e = edges[G[u][i]];
                if (d[e.to] > d[u] + e.dist) {
                    d[e.to] = d[u] + e.dist;
                    p[e.to] = G[u][i];
                    if (!inq[e.to]) {
                        q.push(e.to); inq[e.to] = true; 
                        if (++cnt[e.to] > n) return false;
                    }
                }
            }
        }
        return true;
    }

};

SPFA solver;

int main() {
    int n, m, a, b, c;
    while(cin >> m >> n) {
        solver.init(n);
        while(m--) {
            cin >> a >> b >> c;
            solver.AddEdge(a, b, c);
            solver.AddEdge(b, a, c);
        }
        solver.spfa(1);
        cout << solver.d[n] << endl;
    }
    return 0;
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页