반응형
# Problem
해커 김지민은 잘 알려진 어느 회사를 해킹하려고 한다. 이 회사는 N개의 컴퓨터로 이루어져 있다. 김지민은 귀찮기 때문에, 한 번의 해킹으로 여러 개의 컴퓨터를 해킹 할 수 있는 컴퓨터를 해킹하려고 한다. 이 회사의 컴퓨터는 신뢰하는 관계와, 신뢰하지 않는 관계로 이루어져 있는데, A가 B를 신뢰하는 경우에는 B를 해킹하면, A도 해킹할 수 있다는 소리다. 이 회사의 컴퓨터의 신뢰하는 관계가 주어졌을 때, 한 번에 가장 많은 컴퓨터를 해킹할 수 있는 컴퓨터의 번호를 출력하는 프로그램을 작성하시오. 입력첫째 줄에, N과 M이 들어온다. N은 10,000보다 작거나 같은 자연수, M은 100,000보다 작거나 같은 자연수이다. 둘째 줄부터 M개의 줄에 신뢰하는 관계가 A B와 같은 형식으로 들어오며, "A가 B를 신뢰한다"를 의미한다. 컴퓨터는 1번부터 N번까지 번호가 하나씩 매겨져 있다. 출력첫째 줄에, 김지민이 한 번에 가장 많은 컴퓨터를 해킹할 수 있는 컴퓨터의 번호를 오름차순으로 출력한다. ![]() |
# My Answer - 시간 초과
import collections
n,m = map(int,input().split())
rel=[[] for _ in range(n+1)]
for _ in range(m):
a,b = map(int,input().split())
rel[b].append(a)
visited=[]
queue = collections.deque()
def bfs():
while(queue):
q = queue.popleft()
visited.append(q)
for j in rel[q]:
if j not in visited:
queue.append(j)
result=[]
m=0
for k in range(n+1):
visited=[]
queue=collections.deque([k])
bfs()
result.append((k,len(visited)-1))
m = max(m,len(visited)-1)
for c in result:
if c[1] ==m:
print(c[0],end=' ')
# Solution
from collections import deque
n, m = map(int, input().split())
adj = [[] for _ in range(n + 1)]
for _ in range(m):
x, y = map(int, input().split())
adj[y].append(x)
def bfs(v):
q = deque([v])
visited = [False] * (n + 1)
visited[v] = True
count = 1
while q:
v = q.popleft()
for e in adj[v]:
if not visited[e]:
q.append(e)
visited[e] = True
count += 1
return count
result = []
max_value = -1
for i in range(1, n + 1):
c = bfs(i)
if c > max_value:
result = [i]
max_value = c
elif c == max_value:
result.append(i)
max_value = c
for e in result:
print(e, end=" ")
반응형
'Algorithm > 백준 알고리즘 풀이' 카테고리의 다른 글
[Baekjoon] 5585. 거스름돈 (0) | 2021.04.27 |
---|---|
[Baekjoon] 10282. 해킹 (0) | 2021.04.27 |
[Baekjoon] 1012. 유기농 배추 (0) | 2021.04.23 |
[Baekjoon] 2606. 바이러스 (DFS,BFS) (0) | 2021.04.23 |
[Baekjoon] 1697. 숨바꼭질 (0) | 2021.04.23 |