Skip to content

Commit

Permalink
Shorter toposort (#276)
Browse files Browse the repository at this point in the history
  • Loading branch information
lrvideckis authored Oct 23, 2024
1 parent dccc967 commit 3a59551
Showing 1 changed file with 5 additions and 11 deletions.
16 changes: 5 additions & 11 deletions content/graph/TopoSort.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,10 @@
#pragma once

vi topoSort(const vector<vi>& gr) {
vi indeg(sz(gr)), ret;
vi indeg(sz(gr)), q;
for (auto& li : gr) for (int x : li) indeg[x]++;
queue<int> q; // use priority_queue for lexic. largest ans.
rep(i,0,sz(gr)) if (indeg[i] == 0) q.push(i);
while (!q.empty()) {
int i = q.front(); // top() for priority queue
ret.push_back(i);
q.pop();
for (int x : gr[i])
if (--indeg[x] == 0) q.push(x);
}
return ret;
rep(i,0,sz(gr)) if (indeg[i] == 0) q.push_back(i);
rep(j,0,sz(q)) for (int x : gr[q[j]])
if (--indeg[x] == 0) q.push_back(x);
return q;
}

0 comments on commit 3a59551

Please sign in to comment.