-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
🧑💻 improves the topological sorting algorithm
- Loading branch information
Showing
4 changed files
with
40 additions
and
35 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
const int maxn(1'00'000); | ||
int n, m; | ||
vi g[maxn]; | ||
|
||
int not_found = 0, found = 1, processed = 2; | ||
int state[maxn]; | ||
|
||
bool dfs(int u, vi &order) { | ||
if (state[u] == processed) return true; | ||
if (state[u] == found) return false; | ||
|
||
state[u] = found; | ||
|
||
for (auto v : g[u]) { | ||
if (not dfs(v, order)) return false; | ||
} | ||
|
||
state[u] = processed; | ||
order.emplace_back(u); | ||
|
||
return true; | ||
} | ||
|
||
vi topo_sort() { | ||
vi order; | ||
memset(state, 0, sizeof state); | ||
|
||
for (int u = 0; u < n; u++) { | ||
if (state[u] == not_found and not dfs(u, order)) | ||
return {}; | ||
} | ||
|
||
reverse(all(order)); | ||
return order; | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
\subsection{Topological Sorting (Tarjan)} | ||
|
||
Finds a the topological order for the graph, if there is no such order it means the graph is cyclic, then it returns an empty vector | ||
|
||
$O(V + E)$ |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.