-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFloyd.cpp
154 lines (107 loc) · 2.04 KB
/
Floyd.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#pragma warning(disable : 6262)
#include <iostream>
#include <math.h>
#include <algorithm>
#include <conio.h>
#include <vector>
#include <iterator>
#include <stack>
using namespace std;
const int N = 1e4 + 9;
const int oo = 1e7 + 9;
int weight[N][N];
int trace[N][N];
int n, m;
void Init(int& n, int& m);
void Floyd();
void Paths(int u, int v);
bool negativeCycle(int n);
void traceCycle();
int main()
{
clock_t start, end;
double time_use;
Init(n, m);
start = clock();
Floyd();
bool checkNegative = negativeCycle(n);
if (!checkNegative)
{
cout << "\nShortest Path from 1 --> " << n << " : ";
cout << weight[1][n] << '\n';
cout << "\nPath : ";
Paths(1, n);
}
else
{
traceCycle();
}
end = clock();
time_use = (double)(end - start) / CLOCKS_PER_SEC;
cout << "Run time : " << time_use << endl;
return 0;
}
void Init(int& n, int& m)
{
cin >> n >> m;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
weight[i][j] = oo;
for (int i = 1; i < N; i++)
weight[i][i] = 0;
for (int i = 0; i < m; ++i)
{
int u, v, w;
cin >> u >> v >> w;
weight[u][v] = w;
//weight[v][u] = w;
trace[u][v] = v;
//trace[v][u] = u;
}
}
void Floyd()
{
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
if (weight[i][j] > weight[i][k] + weight[k][j])
{
weight[i][j] = weight[i][k] + weight[k][j];
trace[i][j] = trace[i][k];
}
}
}
void Paths(int u, int v)
{
int Save[N] = { 0 };
vector<int> path;
do {
path.push_back(u);
u = trace[u][v];
} while (path.back() != v);
for (int u = 0; u < path.size(); u++)
{
if (u != path.size() - 1)
cout << path[u] << " --> ";
else cout << path[u] << "\n\n";
}
}
bool negativeCycle(int n)
{
bool checkNegative = false;
for (int i = 1; i <= n; ++i)
if (weight[i][i] < 0)
checkNegative = true;
return checkNegative;
}
void traceCycle()
{
bool checkCycle = negativeCycle(n);
if (!checkCycle)
{
cout << "NO NEGATIVE CYCLE FOUND.\n";
return;
}
cout << "GRAPH HAS NEGATIVE CYCLE .\n";
}