Skip to content

Commit

Permalink
Shorter toposort (kth-competitive-programming#276)
Browse files Browse the repository at this point in the history
  • Loading branch information
lrvideckis authored and Aplietexe committed Oct 28, 2024
1 parent 659e6e3 commit 6eb6238
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 (ll x : li) indeg[x]++;
queue<ll> q; // use priority_queue for lexic. largest ans.
fore(i,0,SZ(gr)) if (indeg[i] == 0) q.push(i);
while (!q.empty()) {
ll i = q.front(); // top() for priority queue
ret.pb(i);
q.pop();
for (ll x : gr[i])
if (--indeg[x] == 0) q.push(x);
}
return ret;
fore(i,0,SZ(gr)) if (indeg[i] == 0) q.pb(i);
for(int j = 0; j < SZ(q); j++) for (ll x : gr[q[j]])
if (--indeg[x] == 0) q.pb(x);
return q;
}

0 comments on commit 6eb6238

Please sign in to comment.