-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbt_dijkstra.cpp
92 lines (71 loc) · 1.31 KB
/
bt_dijkstra.cpp
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
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MOD 1000000007
typedef unsigned long long ull;
#define rep(i,n) for(ll i=0;i<n;i++)
#define INF INT_MAX
typedef pair<ll,ll> pii;
class Graph
{
int v;
list<pii> *adj;
public:
Graph(int v);
void addedge(int v,int w,int weight);
void dijkstra(int src);
};
Graph :: Graph(int v)
{
this->v=v;
adj = new list<pii> [v];
}
void Graph :: addedge(int v,int w,int weight)
{
adj[v].push_back(make_pair(weight,w));
adj[w].push_back(make_pair(weight,v));
}
void Graph :: dijkstra(int src)
{
int dist[v];
bool visited[v];
for(int i=0;i<v;i++)
{
dist[i]=INT_MAX;visited[i]=false;
}
dist[src]=0;
priority_queue<pii,vector<pii>,greater<pii> > q;
q.push(make_pair(0,src));
while(!q.empty())
{
int u=q.top().second;
q.pop();
if(visited[u])
continue;
list<pii> :: iterator it;
visited[u]=true;
for(it=adj[u].begin();it!=adj[u].end();it++)
{
int v=(*it).second;
int currweight=(*it).first;
if(!visited[v] and dist[u]+currweight<dist[v])
{
dist[v]=dist[u]+currweight;
q.push(make_pair(dist[v],v));
}
}
}
for(int i=0;i<v;i++)
cout<<dist[i]<<" ";
}
int main()
{
Graph g(4);
g.addedge(0,1,1);
g.addedge(0,3,4);
g.addedge(0,2,9);
g.addedge(1,3,1);
g.addedge(2,3,2);
g.dijkstra(0);
return 0;
}