File: bellman_ford_algorithm.cpp

package info (click to toggle)
seqan2 2.5.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 228,748 kB
  • sloc: cpp: 257,602; ansic: 91,967; python: 8,326; sh: 1,056; xml: 570; makefile: 229; awk: 51; javascript: 21
file content (46 lines) | stat: -rw-r--r-- 1,522 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <seqan/graph_algorithms.h>

using namespace seqan2;

int main()
{
    typedef Graph<Directed<> > TGraph;
    typedef VertexDescriptor<TGraph>::Type TVertexDescriptor;
    typedef Size<TGraph>::Type TSize;

    // Create graph with 10 directed edges (0,1), (0,3), ...
    TSize numEdges = 10;
    TVertexDescriptor edges[] = {0, 1, 0, 3, 1, 2, 1, 3, 2, 4, 3, 1, 3, 2, 3, 4, 4, 0, 4, 2};
    TGraph g;
    addEdges(g, edges, numEdges);

    // Print graph.
    std::cout << g << "\n";

    // Create external edge property map and assign to graph.
    unsigned weights[] =    {10, 5, 1, 2, 4, 3, 9, 2, 7, 6};
    String<unsigned> weightMap;
    assignEdgeMap(weightMap, g, weights);

    // Run Bellman-Ford algorithm from vertex 0.  NB: Ford-Fulkerson also
    // detects negative cycles.
    String<unsigned int> predMap;
    String<unsigned int> distMap;
    bool noNegativeCycle = bellmanFordAlgorithm(predMap, distMap, g, 0, weightMap);

    // Print result to stdout.
    std::cout << "Single-Source Shortest Paths: " << "\n"
              << "Graph without negative cycles? " << noNegativeCycle << "\n";
    typedef Iterator<TGraph, VertexIterator>::Type TVertexIterator;
    TVertexIterator it(g);
    while (!atEnd(it))
    {
        std::cout << "Path from 0 to " << getValue(it) << ": ";
        _printPath(g, predMap, (TVertexDescriptor) 0, getValue(it));
        std::cout << " (Distance: " << getProperty(distMap, getValue(it)) << ")\n";
        goNext(it);
    }

    return 0;
}