From 3a595515b6d372d8cc12c6cdfd0d9b52fa448019 Mon Sep 17 00:00:00 2001 From: Luke Videckis Date: Wed, 23 Oct 2024 14:42:25 -0700 Subject: [PATCH] Shorter toposort (#276) --- content/graph/TopoSort.h | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/content/graph/TopoSort.h b/content/graph/TopoSort.h index 281ac5ccc..ba94bf349 100644 --- a/content/graph/TopoSort.h +++ b/content/graph/TopoSort.h @@ -12,16 +12,10 @@ #pragma once vi topoSort(const vector& gr) { - vi indeg(sz(gr)), ret; + vi indeg(sz(gr)), q; for (auto& li : gr) for (int x : li) indeg[x]++; - queue 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; }