Last active
May 30, 2021 07:33
-
-
Save sauravgpt/462a1d3f744c85e8c8e5ea288b11e8e0 to your computer and use it in GitHub Desktop.
Minimum time taken by each job to be completed given by a Directed Acyclic Graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Author: Saurav Kumar Gupta | |
Problem: Minimum time taken by each job to be completed given by a Directed Acyclic Graph | |
Data Structures: Queue, Array | |
*/ | |
#include "./../my_lib.h" | |
vector<int> adj[100005]; | |
void findMinTime(int V) { | |
vector<int> indegree(V + 1, 0); | |
for (int i = 1; i <= V; i++) { | |
for (int it : adj[i]) { | |
indegree[it]++; | |
} | |
} | |
vector<int> dist(V + 1, INT_MAX); | |
queue<int> Q; | |
for (int i = 1; i <= V; i++) { | |
if (indegree[i] == 0) { | |
Q.push(i); | |
dist[i] = 1; | |
} | |
} | |
while (!Q.empty()) { | |
int node = Q.front(); Q.pop(); | |
for (int it : adj[node]) { | |
indegree[it]--; | |
if (indegree[it] == 0) { | |
dist[it] = dist[node] + 1; | |
Q.push(it); | |
} | |
} | |
} | |
for (int d : dist) cout << d << " "; | |
} | |
int main() { | |
int V, m; | |
cin >> V >> m; | |
int a, b; | |
for (int i = 1; i <= m; i++) { | |
cin >> a >> b; | |
adj[a].push_back(b); | |
// adj[b].push_back(a); | |
} | |
findMinTime(V); | |
} | |
/* | |
Input: | |
10 | |
13 | |
1 3 | |
1 4 | |
1 5 | |
2 3 | |
2 8 | |
2 9 | |
3 6 | |
4 6 | |
4 8 | |
6 7 | |
7 8 | |
5 8 | |
8 10 | |
Output: | |
1 1 2 2 2 3 4 5 2 6 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment