Skip to content

Commit db9ae57

Browse files
committed
장난감 조립
1 parent 295411b commit db9ae57

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

JongHo/BOJ/2637.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import sys
2+
from collections import deque
3+
input = sys.stdin.readline
4+
5+
n = int(input())
6+
m = int(input())
7+
8+
indegree = [0] * (n + 1) # 간선 정보
9+
10+
edge = [[] for _ in range(n + 1)] # 연결 그래프 초기화
11+
12+
for _ in range(m):
13+
x, y, k = map(int, input().split()) # y부품 k개가 -> x가 됨
14+
15+
indegree[x] += 1 # 간선 개수 추가
16+
edge[y].append((x, k))
17+
18+
lines = [[0] * (n + 1) for _ in range(n+1)] # 각 기본 부품이 몇 개 있는지 (n개로 뒀지만 어차피 다음 코드에 기본 부품밖에 안 셈)
19+
20+
for i in range(1, n + 1):
21+
if indegree[i] == 0: # 간선이 처음에 없으면 기본부품이다.
22+
lines[i][i] += 1 # 기본부품은 자기 자신의 개수 1로 설정.
23+
24+
q = deque() # 양방향 처리를 위해 deque사용.
25+
26+
for j in range(1, n + 1):
27+
if indegree[j] == 0: # 간선이 없는 부품은 q에 넣어준다.
28+
q.append(j)
29+
30+
while q:
31+
now = q.popleft() # 현재 부품
32+
33+
# 그 부품이랑 연결된 중간 부품들 간선개수 줄이고, 부품개수 업데이트
34+
for i in edge[now]:
35+
next, cost = i
36+
indegree[next] -= 1
37+
38+
# 다음 부품의 간선이 없어지면 q에 넣음
39+
if indegree[next] == 0:
40+
q.append(next)
41+
# 다음 부품의 부품개수 = 현재 부품 * 이뤄지는 개수
42+
for j in range(1, n + 1):
43+
lines[next][j] += lines[now][j] * cost
44+
45+
# 완제품의 부품들을 enumerate로 돌면서 0개 이상이면 부품 번호와 개수 출력
46+
for a, b in enumerate(lines[n]):
47+
if b > 0:
48+
print(a, b)

0 commit comments

Comments
 (0)