c_cpp 在Graph |中检测负循环(贝尔曼福特)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 在Graph |中检测负循环(贝尔曼福特)相关的知识,希望对你有一定的参考价值。

// https://www.geeksforgeeks.org/detect-negative-cycle-graph-bellman-ford/
#include <iostream>
using namespace std;
#define inf INT_MAX

struct Edge {
    int src, dest, weight;
};
struct Graph {
    int v,e;
    struct Edge *edge;
};
struct Graph *create (int v, int e) {
    struct Graph *g= new Graph;
    g->v= v;
    g->e= e;
    g->edge= new Edge[e];
    return g;
};

bool NegCycle (struct Graph *g, int s) {
    int v= g->v, e= g->e;
    int dist[v];
    for (int i=0;i <v; i++)
        dist[i]= inf;
    dist[s]= 0;

    for (int i=0; i< v-1; i++) {
        for (int j=0; j<e; j++) {
            int u= g->edge[j].src;
            int v= g->edge[j].dest;
            int w= g->edge[j].weight;

            if (dist[u] != inf && dist[v] > dist[u]+w)
                dist[v] = dist[u]+w;
        }
    }
    for (int j=0; j<e; j++) {
        int u= g->edge[j].src;
        int v= g->edge[j].dest;
        int w= g->edge[j].weight;

        if (dist[u] != inf && dist[v] > dist[u]+w)
            return 1;
    }
    return 0;
}

int main() {
    int v=5, e= 8;
    struct Graph *graph= create(v, e);
    graph->edge[0].src = 0;
    graph->edge[0].dest = 1;
    graph->edge[0].weight = -1;

    // add edge 0-2 (or A-C in above figure)
    graph->edge[1].src = 0;
    graph->edge[1].dest = 2;
    graph->edge[1].weight = 4;

    // add edge 1-2 (or B-C in above figure)
    graph->edge[2].src = 1;
    graph->edge[2].dest = 2;
    graph->edge[2].weight = 3;

    // add edge 1-3 (or B-D in above figure)
    graph->edge[3].src = 1;
    graph->edge[3].dest = 3;
    graph->edge[3].weight = 2;

    // add edge 1-4 (or A-E in above figure)
    graph->edge[4].src = 1;
    graph->edge[4].dest = 4;
    graph->edge[4].weight = 2;

    // add edge 3-2 (or D-C in above figure)
    graph->edge[5].src = 3;
    graph->edge[5].dest = 2;
    graph->edge[5].weight = 5;

    // add edge 3-1 (or D-B in above figure)
    graph->edge[6].src = 3;
    graph->edge[6].dest = 1;
    graph->edge[6].weight = 1;

    // add edge 4-3 (or E-D in above figure)
    graph->edge[7].src = 4;
    graph->edge[7].dest = 3;
    graph->edge[7].weight = -3;

    NegCycle(graph, 0)? cout<< "Yes!": cout<< "No!";
}

以上是关于c_cpp 在Graph |中检测负循环(贝尔曼福特)的主要内容,如果未能解决你的问题,请参考以下文章

贝尔曼福特实现 C++

c_cpp 使用颜色在有向图中检测循环

c_cpp 检测链表中循环或循环的起始节点

检测图中是不是存在负循环的最快算法

c_cpp 检测有向图中的循环

使用 find 和 Union 检测 Graph 中的循环