-
Notifications
You must be signed in to change notification settings - Fork 0
/
14567.py
43 lines (33 loc) ยท 1.31 KB
/
14567.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# -*- coding: utf-8 -*-
# ๊ฐ ๋
ธ๋์ ๊ดํด์ ์ธ์ดํด์ด ์กด์ฌํ์ง ์๋ ๋ฌธ์ ์ด๋ฏ๋ก ์์ ์ ๋ ฌ๋ก ํ์ด
# indegree๋ฅผ ํ์ธํ๊ธฐ ์ํ ๋์
๋๋ฆฌ(deg)์ ์ ๋ต์ ์ํ ๋ฐฐ์ด(ans)
# ๊ฐ ๊ณผ๋ชฉ์ ๋ํ ์ซ์๋ฅผ ํค ๊ฐ์ผ๋ก value ๊ฐ์ [๋ค์์ ๋ค์ ์ ์๋ ๊ณผ๋ชฉ, indegree]๋ก ์ค์
# N๊ฐ ๋งํผ ๊ณผ๋ชฉ์ ๊ด๊ณ๋ฅผ ๋ฐ๊ณ B ๊ฐ์ผ๋ก ๋ค์ด์จ ๊ณผ๋ชฉ์ indgree+=1
# ์ด๊ธฐ์ indgree๊ฐ 0์ธ ๊ณผ๋ชฉ๋ค์ ํ์ ์ถ๊ฐ
# ํ๊ฐ empty์ผ ๋๊น์ง popํ์ฌ ํด๋น ๊ณผ๋ชฉ ๋ค์์ ์๊ฐํ ๊ณผ๋ชฉ์ ๋ํ indgree๊ฐ์ -1ํด์ฃผ๊ณ ๊ทธ ๊ณผ๋ชฉ์ indgree๊ฐ 0์ด ๋ ๊ฒฝ์ฐ
# ํด๋น ๊ณผ๋ชฉ์ ๋ํ ans์ ์ ์๊ฐ ๊ณผ๋ชฉ์ ans๋ฅผ ๋ํด์ฃผ๊ณ ํ์ ์ถ๊ฐํ๋ค.
import sys
from collections import deque
N, M = map(int, sys.stdin.readline().split())
deg = {}
ans = []
q = deque()
for sub in range(1, N+1):
deg[sub] = [[], 0]
ans.append(1)
for _ in range(M):
A, B = map(int, sys.stdin.readline().split())
deg[A][0].append(B)
deg[B][1] += 1
for key in deg.keys():
if deg[key][1] == 0: q.append(key)
while q:
key_ = q.popleft()
for elem in deg[key_][0]:
if deg[elem][1] > 0: deg[elem][1] -= 1
if deg[elem][1] == 0:
q.append(elem)
ans[elem-1] += ans[key_-1]
else: continue
deg[key_][0] = []
print(ans)