๐Ÿค–/๋ฐฑ์ค€

๋ฐฑ์ค€ 1766: ๋ฌธ์ œ์ง‘ (Python)

sssbin 2022. 8. 5. 23:11

 

https://www.acmicpc.net/problem/1766

 

1766๋ฒˆ: ๋ฌธ์ œ์ง‘

์ฒซ์งธ ์ค„์— ๋ฌธ์ œ์˜ ์ˆ˜ N(1 ≤ N ≤ 32,000)๊ณผ ๋จผ์ € ํ‘ธ๋Š” ๊ฒƒ์ด ์ข‹์€ ๋ฌธ์ œ์— ๋Œ€ํ•œ ์ •๋ณด์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ M๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ ๋‘ ์ •์ˆ˜์˜ ์ˆœ์„œ์Œ A,B๊ฐ€ ๋นˆ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ

www.acmicpc.net

 

์œ„์ƒ์ •๋ ฌ์„ ์ด์šฉํ•ด์„œ ํ’€๋ฉด ๋˜๋Š”๋ฐ

'๋จผ์ € ํ‘ธ๋Š” ๊ฒƒ์ด ์ข‹์€ ๋ฌธ์ œ'์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๊ฐ„์„ ์œผ๋กœ ์ €์žฅํ•˜๊ณ 

๊ฐ€๋Šฅํ•˜๋ฉด ์‰ฌ์šด ๋ฌธ์ œ๋ฅผ ๋จผ์ € ํ’€์–ด์•ผ ํ•˜๋Š”๋ฐ ๋‚œ์ด๋„๋Š” 1๋ฒˆ~n๋ฒˆ ์ฐจ๋ก€๋Œ€๋กœ ๋˜์–ด ์žˆ์œผ๋‹ˆ

ํ๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด์„œ ์“ฐ๋ฉด ๋œ๋‹ค. -> ์šฐ์„ ์ˆœ์œ„ ํ ์‚ฌ์šฉํ•จ

 

# ์šฐ์„ ์ˆœ์œ„ํ
from queue import PriorityQueue

# ์ƒ์„ฑ
q = PriorityQueue()
q = PriorityQueue(maxsize = 8)  # ์ตœ๋Œ€ ํฌ๊ธฐ 8

# ์›์†Œ ์ถ”๊ฐ€
q.put(1)
# ์›์†Œ ์‚ญ์ œ
q.get()

# ํ์˜ ์‚ฌ์ด์ฆˆ๋ฅผ ๋ฐ˜ํ™˜
q.qsize()
# ํ๊ฐ€ ๋น„์–ด์žˆ์œผ๋ฉด True, ๋น„์–ด์žˆ์ง€ ์•Š์œผ๋ฉด False ๋ฐ˜ํ™˜
q.empty()
# ํ๊ฐ€ ๊ฐ€๋“ ์ฐจ์žˆ์œผ๋ฉด True, ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด False ๋ฐ˜ํ™˜
q.full()

 

from queue import PriorityQueue
import sys
input = sys.stdin.readline

n, m = map(int, input().split())

info = [[] for _ in range(n+1)]
indegree = [0] * (n+1)

for _ in range(m):
    a, b = map(int, input().split())
    info[a].append(b)
    indegree[b] += 1

q = PriorityQueue()
res = []

for i in range(1, n+1):
    if indegree[i] == 0:
        q.put(i)

while q.empty() is False:
    now = q.get()
    res.append(now)
    for i in info[now]:
        indegree[i] -= 1
        if indegree[i] == 0:
            q.put(i)

for i in res:
    print(i, end=' ')