Bellman-Ford算法

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>

using namespace std;
const int maxn = 100000 + 5;
const int INF = 99999999;

int d[maxn], cnt[maxn], n, m;    //n,m分别是定点数目以及边数
bool inq[maxn];

struct Edge {
    int from, to, dist;
    Edge(int u, int v, int d) : from(u), to(v), dist(d) {}
};
vector<Edge> edges;
vector<int> G[maxn];

bool bellman_ford(int s) {
    queue<int> q;
    memset(cnt, 0, sizeof(cnt));
    memset(inq, 0, sizeof(inq));
    for(int i = 0; i < n; i++)  d[i] = INF;
    d[s] = 0;   inq[s] = true;
    q.push(s);

    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[u] < INF && 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;
}

int main()
{

    return 0;
}

你可能感兴趣的:(Bellman-Ford算法)