본문 바로가기

BOJ 알고리즘 (패캠)/그래프

1325번: 효율적인해킹 (그래프, BFS, DFS) - Fastcampus

www.acmicpc.net/problem/1325

 

1325번: 효율적인 해킹

첫째 줄에, N과 M이 들어온다. N은 10,000보다 작거나 같은 자연수, M은 100,000보다 작거나 같은 자연수이다. 둘째 줄부터 M개의 줄에 신뢰하는 관계가 A B와 같은 형식으로 들어오며, "A가 B를 신뢰한�

www.acmicpc.net

# PyPy3
import sys
from collections import deque


def bfs(start):
    qu = deque([start])
    visited = [0] * len(graph)

    cnt = 0
    while qu:
        node = qu.popleft()
        if not visited[node]:
            visited[node] = 1
            cnt += 1
            for e in graph[node]:
                qu.append(e)
    return cnt


N, M = map(int, input().split())
graph = [[] for _ in range(N+1)]
for _ in range(M):
    a, b = map(int, sys.stdin.readline().split())
    graph[b].append(a)

ans, max_v = [], -1e9
for i in range(1, N+1):
    cnt = bfs(i)
    if cnt > max_v:
        max_v = cnt
        ans = [i]
    elif cnt == max_v:
        ans.append(i)
print(" ".join(map(str, ans)))