참조
https://velog.io/@gkdis6/알고리즘-강한-연결-요소-추출-알고리즘-Strongly-Connected-Component
https://mobuk.tistory.com/120
https://velog.io/@namsh1125/%ED%83%80%EC%9E%94-%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98
백준 2150
import sys
sys.setrecursionlimit(10**8)
input=sys.stdin.readline
V,E=map(int,input().split())
graph=[[] for _ in range(V+1)]
parents=[-1]*(V+1)
for _ in range(E):
a,b=map(int,input().split())
graph[a].append(b)
stk=[]
visit=[0]*(V+1)
id=0
res=[]
def func(now):
global id
id+=1
parents[now]=id
stk.append(now)
visit[now]=1
parent=parents[now]
for next in graph[now]:
if parents[next]==-1:
parent=min(parent,func(next))
elif visit[next]:
parent=min(parent,parents[next])
if parent==parents[now]:
scc=[]
while True:
node=stk.pop()
visit[node]=0
scc.append(node)
if now==node:
break
res.append(sorted(scc)+[-1])
return parent
for i in range(1,V+1):
if parents[i]==-1:
func(i)
res.sort()
print(len(res))
for i in res:
print(*i)
암기하기 쉽게 변형(백준 11278)
N,M=map(int,input().split())
graph=[[] for _ in range(2*N+1)]
for i in range(M):
x,y=map(int,input().split())
graph[-x].append(y)
graph[-y].append(x)
stk=[]
visit=[0]*(2*N+1)
finish=[0]*(2*N+1)
scc_idx=[0]*(2*N+1)
id=1
scc_id=1
def func(now):
global id,scc_id
parent=id
visit[now]=id
id+=1
stk.append(now)
for next in graph[now]:
if not visit[next]:
parent=min(parent,func(next))
if not finish[next]:
parent=min(parent,visit[next])
if parent==visit[now]:
while stk:
top=stk.pop()
finish[top]=1
scc_idx[top]=scc_id
if top==now:
break
scc_id+=1
return parent
for i in range(1,2*N+1):
if not visit[i]:
func(i)
res=[0]*(N)
for i in range(1,N+1):
if scc_idx[i]==scc_idx[-i]:
print(0)
break
if scc_idx[i]<scc_idx[-i]:
res[i-1]=1
else:
print(1)
print(*res)