๋ฌธ์
https://www.acmicpc.net/problem/21276
๋ฐฑ์ค ๋ฌธ์ ์ง - 0x1A๊ฐ - ์์ ์ ๋ ฌ
์๊ณ ๋ฆฌ์ฆ: ์ ๋ ฌ, ํด์๋ฅผ ์ฌ์ฉํ ์งํฉ๊ณผ ๋งต, ๋ฐฉํฅ ๋น์ํ ๊ทธ๋ํ, ์์ ์ ๋ ฌ
ํ์ด

๐จ ์ฃผ์ํด์ผํ ๋ถ๋ถ์ ํ์๋ค์ด "์ง๊ณ ์กฐ์(=๋ถ๋ชจ)"๋ฅผ ๊ธฐ์ตํ๊ณ ์๋๊ฒ ์๋๋ผ๋ ๊ฒ์ด๋ค.
๊ทธ๋ฅ ๋ณธ์ธ์ ์กฐ์ ์ค ์๋ฌด๋๋ฅผ ์ ํํ๊ฒ์ด๋ฏ๋ก, ํด๋น ์กฐ์์ ๋ฒ์๋ (์์กฐ ~ ๋ถ๋ชจ)์ธ ์
์ด๋ค.
๊ณ ๋ก ์ด ๋ฌธ์ ๋ฅผ DFS๋ก ํผ๋ค๋ฉด ์กฐ๊ฑด์ฒ๋ฆฌ๊ฐ ๊น๋ค๋ก์์ง๊ฒ์ด๋ค...(์ผ๋จ ๋๋ ์๊ฐ์ด๊ณผ๋ก ์คํจํจ)
๋ฐ๋ผ์ BFS๋ก ํ์ดํ๋๋ฐ, ์งํ ๊ณผ์ ์ ๋ค์๊ณผ ๊ฐ๋ค.
- ์กฐ์ → ์์ ํํ๋ก ์ง์ ์ฐจ์๋ฅผ ์ ๋ฆฌํด์ค
- ์ง์ ์ฐจ์๊ฐ 0์ธ ์ฌ๋๋ค = ์์กฐ ์ด๋ฏ๋ก, ์์กฐ๋ค์ ๋ชจ๋ queue์ ์ฝ์
- ์ง๊ณ์์๋ค์ ๊ธฐ๋กํ ๋ฆฌ์คํธ๋ฅผ ๋ฐ๋ก ์์ฑ ํ BFS ์คํ
- queue๊ฐ ๋น ๋๊น์ง ์๋์ ๊ณผ์ ์ ๋ฐ๋ณต
- queue์์ ๋ ธ๋๋ฅผ ๊บผ๋
- ํด๋น ๋
ธ๋์ ์์๋ค์ ํ๋์ฉ ์ํ
- ์์์ ์ง์ ์ฐจ์๋ฅผ 1 ๊ฐ์์ํด
- ๊ฐ์ ํ ์ง์ ์ฐจ์๊ฐ 0์ด ๋๋ค๋ฉด, ํ์ฌ ๋ ธ๋์ ์ง๊ณ์์์ด๋ผ๋ ์๋ฏธ.
- ๊ธฐ๋ก์ฉ ๋ฆฌ์คํธ์ ์ ์ฅ ํ queue์ ์์ ๋ ธ๋ ์ฝ์
- BFS๊ฐ ๋๋๋ฉด ์์กฐ์ ๊ฐฏ์, ์ ๋ ฌ๋ ์์กฐ ์ด๋ฆ๋ค์ ์ถ๋ ฅ
- ๋ชจ๋ ์ฌ๋์ ์ด๋ฆ์ ์ ๋ ฌ ํ
์ฌ๋์ด๋ฆ ์์์ ์์๋ค...์ ํ์ค์ฉ ์ถ๋ ฅํ๋ฉด ๋
์ซ์๊ฐ ์๋ ๋ฌธ์์ด๋ก ์ฃผ์ด์ง๊ธฐ ๋๋ฌธ์ ๋์
๋๋ฆฌ๋ฅผ ํ์ฉํด์ผํ๋ค.
๋๋ ๊ทธ๋ฅ (์ด๋ฆ→๋ฒํธ), (๋ฒํธ→์ด๋ฆ)์ผ๋ก ๋ณํํ ์ ์๊ฒ๋ ๋งตํํด์คฌ๋๋ฐ, defaultdict๋ฅผ ์ฌ์ฉํ๋๊ฒ ๋ ํธํ ์๋...?
์ทจํฅ๊ป ์ ํํ๋ฉด ๋๊ฒ ๋ค.
์ ์ฒด ์ฝ๋
# ์ง๊ณ ์์-๋ถ๋ชจ ๊ด๊ณ์ ๋
ธ๋๋ค๋ง ์ฃผ์ด์ง๋๊ฒ ์๋.
# ๋ฐ๋ผ์ DFS๋ก ํ์ด ์ ์๊ฐ์ด๊ณผ๊ฐ ๋์จ๋ค. ์ด ๋ฌธ์ ๋ ์ง์
์ฐจ์ + BFS ๋ก ํ์ด์ผ ํต๊ณผํ ์ ์์.
# ๋ฉ๋ชจ๋ฆฌ: 37136KB / ์๊ฐ: 496ms
from sys import stdin
from collections import deque
input = stdin.readline
N = int(input())
names = input().rstrip().split()
# ์ด๋ฆ๊ณผ ๋ฒํธ๋ฅผ ๋งค์นญ์ํด
name_to_num = {name: i for i, name in enumerate(names)} # 1. ์ด๋ฆ -> ๋ฒํธ
num_to_name = {v: k for k, v in name_to_num.items()} # 2. ๋ฒํธ -> ์ด๋ฆ
graph = [[] for _ in range(N)]
in_degree = [0] * N # ์ง์
์ฐจ์๊ฐ 0์ธ ์ฌ๋์ด ์์กฐ
M = int(input())
for _ in range(M):
child, ancester = input().rstrip().split()
child, ancester = name_to_num[child], name_to_num[ancester]
graph[ancester].append(child)
in_degree[child] += 1
# ์ง๊ณ์์๋ค์ ๊ธฐ๋กํ ๋ฆฌ์คํธ
direct_child = [[] for _ in range(N)]
# ์์กฐ๋ค์ ํ์ ๋ฃ๊ณ BFS ์คํ
root = [i for i in range(N) if in_degree[i] == 0]
queue = deque(root)
# ์ง์
์ฐจ์๋ก ์ง๊ณ ์์์ ๊ณ์ฐ
def bfs():
while queue:
curr = queue.popleft()
for node in graph[curr]:
in_degree[node] -= 1
if in_degree[node] == 0: # ์ง์
์ฐจ์๊ฐ 0์ด ๋๋ค๋ฉด ํ์ฌ ๋
ธ๋์ ์ง๊ณ์์์ธ์
direct_child[curr].append(node)
queue.append(node)
bfs()
root = [num_to_name[r] for r in root] # ์์กฐ๋ค์ ๋ฒํธ๋ฅผ ์ด๋ฆ์ผ๋ก ๋ณํ
print(len(root))
print(*sorted(root))
for name in sorted(names):
num = name_to_num[name]
children = sorted(num_to_name[child] for child in direct_child[num])
print(name, len(children), *children)
๊ทธ๋์ ๋ ํธ์์ด๋ ๋ฌธ์์ด ์ง์ฅ์๋ ๋น ์ก๋ค๊ฐ ๊ณ๋ณด๋ ๋ณต์ํ๋ค๊ฐ ์ฐธ ๋ฐ์๋ค. ํ์ดํ ํธ์!