init
This commit is contained in:
commit
851751ea87
82 changed files with 2093 additions and 0 deletions
48
1K.py
Normal file
48
1K.py
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import sys
|
||||
input = sys.stdin.readline
|
||||
line = input().split()
|
||||
if not line:
|
||||
sys.exit()
|
||||
n, m = map(int, line)
|
||||
g = [[] for _ in range(n + 1)]
|
||||
gr = [[] for _ in range(n + 1)]
|
||||
for _ in range(m):
|
||||
u, v = map(int, input().split())
|
||||
g[u].append(v)
|
||||
gr[v].append(u)
|
||||
used = [0] * (n + 1)
|
||||
order = []
|
||||
head = [0] * (n + 1)
|
||||
for i in range(1, n + 1):
|
||||
if not used[i]:
|
||||
stack = [i]
|
||||
used[i] = 1
|
||||
while stack:
|
||||
v = stack[-1]
|
||||
if head[v] < len(g[v]):
|
||||
to = g[v][head[v]]
|
||||
head[v] += 1
|
||||
if not used[to]:
|
||||
used[to] = 1
|
||||
stack.append(to)
|
||||
else:
|
||||
stack.pop()
|
||||
order.append(v)
|
||||
used = [0] * (n + 1)
|
||||
comp = [0] * (n + 1)
|
||||
c = 1
|
||||
for i in reversed(order):
|
||||
if not used[i]:
|
||||
stack = [i]
|
||||
used[i] = 1
|
||||
comp[i] = c
|
||||
while stack:
|
||||
v = stack.pop()
|
||||
for to in gr[v]:
|
||||
if not used[to]:
|
||||
used[to] = 1
|
||||
comp[to] = c
|
||||
stack.append(to)
|
||||
c += 1
|
||||
print(c - 1)
|
||||
print(" ".join(map(str, comp[1:])))
|
||||
Loading…
Add table
Add a link
Reference in a new issue