-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbellmanFord.cpp
More file actions
71 lines (65 loc) · 1.63 KB
/
Copy pathbellmanFord.cpp
File metadata and controls
71 lines (65 loc) · 1.63 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
#include <bits/stdc++.h>
#define INF INT_MAX
using namespace std;
typedef pair<int, int> node;
typedef vector<node> graph;
bool checkNCycle(graph Graph[], int V, vector<int> &weight)
{
for (int u = 0; u < V; ++u)
{
int n = Graph[u].size();
for (int i = 0; i < n; ++i)
{
int v = Graph[u][i].first;
int w = Graph[u][i].second;
if (weight[u] != INF && weight[v] > weight[u] + w)
return true;
}
}
return false;
}
vector<int> bellmanFord(graph Graph[], int V)
{
vector<int> weight(V, INF);
int src = 0;
weight[src] = 0;
for (int k = 0; k < V - 1; ++k)
{
for (int u = 0; u < V; ++u)
{
int n = Graph[u].size();
for (int i = 0; i < n; ++i)
{
int v = Graph[u][i].first;
int w = Graph[u][i].second;
if (weight[u] != INF && weight[v] > weight[u] + w)
weight[v] = weight[u] + w;
}
}
}
return weight;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int V, E;
cin >> V >> E;
graph Graph[V];
for (int i = 0; i < E; ++i)
{
int s, d, w;
cin >> s >> d >> w;
Graph[s].push_back(make_pair(d, w));
}
vector<int> weight = bellmanFord(Graph, V);
for (int i = 0; i < V; ++i)
cout << i << " : " << weight[i] << endl;
if (checkNCycle(Graph, V, weight))
cout << "Negetive Cycle exists" << endl;
else
cout << "Negetive Cycle does not exist" << endl;
return 0;
}