-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathbellmanford.cpp
More file actions
108 lines (99 loc) · 2.28 KB
/
Copy pathbellmanford.cpp
File metadata and controls
108 lines (99 loc) · 2.28 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
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
#include<bits/stdc++.h>
using namespace std;
#define INF 9999
vector<vector<pair<int,int>>> adj(1000);
vector<int>dis;
vector<int>par;
int source;
int pathfind(int dest)
{
if(dest!=source && par[dest]==-1)
{
cout << "Path not found\n";
return 0;
}
if(dest==source)
{
cout << "Path: " << source;
return 0;
}
pathfind(par[dest]);
cout << " " << dest;
}
int main()
{
ifstream input("bellmanford_input.txt");
if(!input.is_open())
{
cout << "File not open!\n";
}
int totalnode,node1,node2,weight;
input>>totalnode;
while(input>>node1>>node2>>weight)
{
adj[node1].push_back(make_pair(node2,weight));
}
/*for(int i=0;i<totalnode;i++)
{
cout << i << ": ";
for(int j=0;j<adj[i].size();j++)
{
cout << adj[i][j].first << "("<<adj[i][j].second<<")->";
}
cout << endl;
}*/
cout << "Enter source: ";
cin>> source;
dis.assign(totalnode,INF);
par.assign(totalnode,-1);
dis[source]=0;
for(int i=0; i<totalnode-1; i++)
{
for(int u=0; u<totalnode; u++)
{
for(int j=0; j<adj[u].size(); j++)
{
pair<int,int> v=adj[u][j];
if(dis[u]==INF)
continue;
if(dis[u]+v.second<dis[v.first])
{
dis[v.first]=dis[u]+v.second;
par[v.first]=u;
}
}
}
}
bool hascycle = false;
for(int u=0; u<totalnode; u++)
{
for(int j=0; j<adj[u].size(); j++)
{
pair<int,int> v=adj[u][j];
if(dis[u]==INF)
continue;
if(dis[u]+v.second<dis[v.first])
{
hascycle = true;
break;
}
}
if(hascycle)
{
break;
}
}
if(hascycle)
{
cout << "The graph has negative cycle\n";
}
else
{
int dest;
cout << "Enter destination: ";
cin>>dest;
cout << "Distance: " << dis[dest] << endl;
pathfind(dest);
}
return 0;
}