-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstras.cpp
More file actions
81 lines (69 loc) · 1.41 KB
/
Dijkstras.cpp
File metadata and controls
81 lines (69 loc) · 1.41 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
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
// defining graph
class Graph
{
int v;
list<pair<int,int> > *adj;
public:
Graph(int v);
void addEdge(int u, int v, int w);
void shortestPath(int s);
};
// allocating memory
Graph::Graph(int v)
{
this->v = v;
adj = new list<pair<int,int> > [v];
}
// adding edge
void Graph::addEdge(int u, int v, int w)
{
adj[u].push_back(make_pair(v,w));
adj[v].push_back(make_pair(u,w));
}
// find shortest paths to all nodes from source vertex
void Graph::shortestPath(int src)
{
set<pair<int,int> > s;
vector<int> dist(v,INF);
s.insert(make_pair(0,src));
dist[src] = 0;
while(!s.empty())
{
pair<int,int> temp = *(s.begin());
s.erase(s.begin());
int u = temp.second;
list<pair<int,int> > :: iterator i;
for(i=adj[u].begin();i!=adj[u].end();++i)
{
int x = (*i).first;
int wt = (*i).second;
if(dist[x]>(dist[u]+wt))
{
if(dist[x]!=INF) s.erase(s.find(make_pair(dist[x],x)));
dist[x] = dist[u]+wt;
s.insert(make_pair(dist[x],x));
}
}
}
cout<<"vertex"<<" "<<"minimum distance from it\n";
for(int i=0;i<v;++i)
cout<<" "<<i<<" "<<dist[i]<<"\n";
}
// NOTE: vertices have values 1 to n.
int main()
{
int n; int e; // verices and edges
cin>>n>>e;
Graph g(n);
for(int i=1;i<=e;i++)
{
int a, b, c;
cin>>a>>b>>c;
g.addEdge(a, b, c);
}
g.shortestPath(0); // change src accordingly...
return 0;
}