-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbellmanFord.cpp
107 lines (81 loc) · 1.98 KB
/
bellmanFord.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include "shortestPath.hpp"
#include "readGraph.hpp"
#include <chrono>
using namespace std;
int main(int argc, char *argv[])
{
if(argc!=4)
{
cout<<"Please enter the graph file, output file and source vertex as command line arguments"<<endl;
return 1;
}
ifstream inFile;
ofstream outFile;
inFile.open(argv[1]);
outFile.open(argv[2]);
if (!inFile)
{
cerr << "Unable to open file"<<endl;
exit(1); // call system to stop
}
string sourceVertex=argv[3];
int** edgeList;
double* weights;
int numEdges;
string* vLabels;
string* eLabels;
int vertices=readGraph(inFile, edgeList, weights, numEdges, vLabels, eLabels);
int source=0;
int i=0;
while(sourceVertex!=vLabels[i])
{
i++;
}
source=i;
//we need dist and prev to pass into bellman-ford
double* distance;
int* previous;
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
int negcyc=bellmanFord(edgeList, weights, vertices, numEdges, source, distance, previous);
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
if(negcyc!=-1)
{
cout<<"Negative Cycle Detected! "<<endl;
cout<<"Total Weight: "<<weights[negcyc]<<endl;
cout<<"Runtime: "<<elapsed_seconds.count()<<"microseconds"<<endl;
outFile<<vertices<<" "<<negcyc-1 <<endl;
for(int i=0; i<vertices;i++)
{
outFile<<vLabels[i]<<endl;
}
int* cycle;
int cycsize=getCycle(negcyc,previous, vertices, cycle);
cout<<"cyclesize: "<<cycsize<<endl;
for(int i=1; i<cycsize;i++)
{
outFile<<cycle[i-1]<<" "<<cycle[i]<<endl;
}
}
else
{
outFile<<vertices<<" "<<6<<endl; //cause pathlength includes own vertex too
for(int i=0; i<vertices;i++)
{
outFile<<vLabels[i]<<endl;
}
outFile<<endl;
for (int i = 0; i < vertices; i++) //cause 1 will be the source
{
if(source!=i)
{
outFile<<source<<" "<<i<<" "<<distance[i]<<" "<<endl;
}
}
}
}