Skip to content

Commit 4e1e9a6

Browse files
committed
add Topological Sort template
1 parent fc7166a commit 4e1e9a6

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

templates/TopoSort.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <cstdio>
2+
3+
const int maxn = 1e5 + 100;
4+
struct node
5+
{
6+
int to, next;
7+
} E[maxn];
8+
int head[maxn], cnt;
9+
inline void add(const int& u, const int& v)
10+
{
11+
E[++cnt].next = head[u], head[u] = cnt, E[cnt].to = v;
12+
}
13+
14+
int n, m;
15+
16+
namespace Topo
17+
{
18+
int in[maxn], q[maxn], qh, qt;
19+
void TopoSort()
20+
{
21+
for (int i = 1; i <= n; ++i) in[i] = 0;
22+
for (int u = 1; u <= n; ++u)
23+
for (int p = head[u]; p; p = E[p].next) ++in[E[p].to];
24+
qh = 1, qt = 0;
25+
for (int i = 1; i <= n; ++i)
26+
if (!in[i]) q[++qt] = i;
27+
while (qh >= qt)
28+
{
29+
int u = q[qh++];
30+
for (int p = head[u]; p; p = E[p].next)
31+
{
32+
int v = E[p].to;
33+
if (--in[v] == 0)
34+
q[++qt] = v;
35+
}
36+
}
37+
}
38+
} // namespace Topo

0 commit comments

Comments
 (0)