-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBellman Ford's Algorithm.cpp
More file actions
73 lines (63 loc) · 1.26 KB
/
Bellman Ford's Algorithm.cpp
File metadata and controls
73 lines (63 loc) · 1.26 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
/*
Bellman Ford's Algorithm
(Undirected)
Time Complexity: O(EV)
*/
#include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int N,M;
cin>>N>>M;
int start;
vector<pair<int,int>>adj[N+1];
for(int m = 0; m<M; m++)
{
int u,v,w;
cin>>u>>v>>w;
adj[u].push_back({v,w});
adj[v].push_back({u,w});
}
cin>>start;
vector<int>dis(N+1, INT_MAX);
dis[start] = 0;
for(int i = 0; i<N-1; i++)
{
for(int u = 1; u<=N; u++)
{
for(auto it: adj[u])
{
int v = it.first;
int w = it.second;
dis[v] = min(dis[v], dis[u]+w);
}
}
}
for(int u = 1; u<=N; u++)
{
for(auto it: adj[u])
{
int v = it.first;
int w = it.second;
if(dis[v] != min(dis[v], dis[u]+w))
{
cout<<"Negative cycle";
}
}
}
for(int i = 1; i<=N; i++)
{
if(i != start)
{
if(dis[i] == INT_MAX)
cout<<-1<<" ";
else
cout<<dis[i]<<" ";
}
}
cout<<endl;
return 0;
}