1
+
2
+ #include < bits/stdc++.h>
3
+ using namespace std ;
4
+ # define INF 0x3f3f3f3f
5
+
6
+ class Graph
7
+ {
8
+ int V;
9
+ list< pair<int , int > > *adj;
10
+
11
+ public:
12
+ Graph (int V);
13
+ void addEdge (int u, int v, int w);
14
+
15
+
16
+ void shortestPath (int s, int W);
17
+ };
18
+
19
+
20
+ Graph::Graph (int V)
21
+ {
22
+ this ->V = V;
23
+ adj = new list< pair<int , int > >[V];
24
+ }
25
+
26
+ void Graph::addEdge (int u, int v, int w)
27
+ {
28
+ adj[u].push_back (make_pair (v, w));
29
+ adj[v].push_back (make_pair (u, w));
30
+ }
31
+
32
+
33
+ void Graph::shortestPath (int src, int W)
34
+ {
35
+ vector<pair<int , list<int >::iterator> > dist (V);
36
+
37
+
38
+ for (int i = 0 ; i < V; i++)
39
+ dist[i].first = INF;
40
+
41
+
42
+ list<int > B[W * V + 1 ];
43
+
44
+ B[0 ].push_back (src);
45
+ dist[src].first = 0 ;
46
+
47
+
48
+ int idx = 0 ;
49
+ while (1 )
50
+ {
51
+
52
+
53
+ while (B[idx].size () == 0 && idx < W*V)
54
+ idx++;
55
+
56
+ if (idx == W * V)
57
+ break ;
58
+
59
+
60
+ int u = B[idx].front ();
61
+ B[idx].pop_front ();
62
+
63
+ for (auto i = adj[u].begin (); i != adj[u].end (); ++i)
64
+ {
65
+ int v = (*i).first ;
66
+ int weight = (*i).second ;
67
+
68
+ int du = dist[u].first ;
69
+ int dv = dist[v].first ;
70
+
71
+ if (dv > du + weight)
72
+ {
73
+
74
+ if (dv != INF)
75
+ B[dv].erase (dist[v].second );
76
+
77
+
78
+ dist[v].first = du + weight;
79
+ dv = dist[v].first ;
80
+
81
+
82
+ B[dv].push_front (v);
83
+
84
+
85
+ dist[v].second = B[dv].begin ();
86
+ }
87
+ }
88
+ }
89
+
90
+ printf (" Vertex Distance from Source\n " );
91
+ for (int i = 0 ; i < V; ++i)
92
+ printf (" %d %d\n " , i, dist[i].first );
93
+ }
94
+
95
+ int main ()
96
+ {
97
+
98
+ int V = 9 ;
99
+ Graph g (V);
100
+
101
+
102
+ g.addEdge (0 , 1 , 4 );
103
+ g.addEdge (0 , 7 , 8 );
104
+ g.addEdge (1 , 2 , 8 );
105
+ g.addEdge (1 , 7 , 11 );
106
+ g.addEdge (2 , 3 , 7 );
107
+ g.addEdge (2 , 8 , 2 );
108
+ g.addEdge (2 , 5 , 4 );
109
+ g.addEdge (3 , 4 , 9 );
110
+ g.addEdge (3 , 5 , 14 );
111
+ g.addEdge (4 , 5 , 10 );
112
+ g.addEdge (5 , 6 , 2 );
113
+ g.addEdge (6 , 7 , 1 );
114
+ g.addEdge (6 , 8 , 6 );
115
+ g.addEdge (7 , 8 , 7 );
116
+
117
+
118
+ g.shortestPath (0 , 14 );
119
+
120
+ return 0 ;
121
+ }
0 commit comments