-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFloyd-Warshall.cpp
More file actions
81 lines (79 loc) · 1.51 KB
/
Floyd-Warshall.cpp
File metadata and controls
81 lines (79 loc) · 1.51 KB
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
//complexity: O(V^3)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
#define MAX 105
#define INF 1e9
vector<vector<int>>graph;
vector<vector<int>>dist;
vector<vector<int>>path;
int V;
void printPath(int s, int t)
{
int b[MAX];
int m = 0;
while (s != t)
{
b[m++] = t;
t = path[s][t];
}
b[m++] = s;
for (int i = m - 1; i >= 0; i--)
cout << b[i] << " ";
}
bool FloyWarshall(vector<vector<int>>& graph, vector<vector<int>>& dist)
{
for(int i=0;i<V;i++)
for (int j = 0; j < V; j++)
{
dist[i][j] = graph[i][j];
if (graph[i][j] != INF && i != j)
{
path[i][j] = i;
}
else
{
path[i][j] = -1;
}
}
for(int k=0;k<V;k++)
for(int i=0;i<V;i++)
for (int j = 0; j < V; j++)
{
if (dist[i][j] > dist[i][k] + dist[k][j])
{
dist[i][j] = dist[i][k] + dist[k][j];
path[i][j] = path[k][j];
}
}
for (int i = 0; i < V; i++)
if (dist[i][i] < 0)
return false;
return true;
}
int main()
{
freopen("INPUT.INP", "rt", stdin);
int temp;
cin >> V;
graph = vector<vector<int>>(V, vector<int>(V));
dist = vector<vector<int>>(V, vector<int>(V));
path = vector<vector<int>>(V, vector<int>(V));
for(int i=0;i<V;i++)
for (int j = 0; j < V; j++)
{
cin >> temp;
if (temp == 0 && i != j)
graph[i][j] = INF;
else
graph[i][j] = temp;
}
FloyWarshall(graph, dist);
int s = 0;
int t = 4;
int result = dist[s][t];
printPath(s, t);
cout << result;
return 0;
}