-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphAdvance.cpp
More file actions
95 lines (82 loc) · 2.18 KB
/
graphAdvance.cpp
File metadata and controls
95 lines (82 loc) · 2.18 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
#include<bits/stdc++.h>
using namespace std;
#define inf (int)1e9
// *TODO*
// Kruskal's algo for Minumun spannin tree (MST)
// Articulation Point
// Bridges in graph
// Tarjan's Algorithm
// shortest path
// if graph is unweighted -> bfs --> O(V+E)
// if directed and acyclic graph (DAG) -> topological sort then relax(u, v) --> O(V+E)
// if graph does not contain -ve weight edges -> Dijkstra --> O(V+E*log(V))
// if graph contains -ve weight edges and no -ve weight cycle -> Bellman Ford --> O(V*E)
void insert(vector<pair<int, int>> adj[], int u, int v, int wg){
adj[u].push_back({v, wg});
}
void print(vector<pair<int, int>> adj[], int v){
for(int i = 0; i < v; i++){
cout << i << " ";
for(auto x : adj[i]){
cout << x.first << " " << x.second << " ";
}
cout << '\n';
}
}
void shortPath(vector<pair<int, int>> adj[], int v, int s){
vector<int> distance(v, inf);
vector<int> indegree(v);
queue<int> q;
vector<int> tAns;
distance[s] = 0;
for(int i = 0; i < v; i++){
for(auto x : adj[i]){
indegree[x.first]++;
}
}
for(int i = 0; i < indegree.size(); i++){
if(indegree[i] == 0){
q.push(i);
}
}
while(!q.empty()){
int x = q.front();
q.pop();
tAns.push_back(x);
for(auto u : adj[x]){
indegree[u.first]--;
if(indegree[u.first] == 0){
q.push(u.first);
}
}
}
for(int x : tAns){
for(auto u : adj[x]){
if(distance[u.first] > distance[x] + u.second){
distance[u.first] = distance[x] + u.second;
}
}
}
for(int x : distance){
(x == inf) ? cout << "-1 " : cout << x << " ";
}
}
// Shortest path in directed ascyclic graph(DAG)
void shortestPath(){
int v = 6;
vector<pair<int, int>> adj[v];
insert(adj, 0, 1, 2);
insert(adj, 0, 4, 1);
insert(adj, 1, 2, 3);
insert(adj, 4, 2, 2);
insert(adj, 4, 5, 4);
insert(adj, 2, 3, 6);
insert(adj, 5, 3, 1);
// print(adj, v);
int source = 0;
shortPath(adj, v, source);
}
int main(){
shortestPath();
return 0;
}