안녕하세요. 모카의 머신러닝 입니다. 이번 포스팅에서는 백준 알고리즘 문제 풀이에 대해 포스팅하도록 하겠습니다.
코드는 이곳을 참고했음을 밝힙니다.
1. Number theory
백준 18352번
https://www.acmicpc.net/problem/18352
import sys
from collections import deque
input = sys.stdin.readline
N, M, K, X = map(int, input().split())
A = [[] for _ in range(N + 1)]
answer = []
visited = [-1] * (N + 1)
def BFS(v):
queue = deque()
queue.append(v)
visited[v] += 1
while queue:
now_Node = queue.popleft()
for i in A[now_Node]:
if visited[i] == -1:
visited[i] = visited[now_Node] + 1
queue.append(i)
for _ in range(M):
S, E = map(int, input().split())
A[S].append(E)
BFS(X)
for i in range(N + 1):
if visited[i] == K:
answer.append(i)
if not answer:
print(-1)
else:
answer.sort()
for i in answer:
print(i)
백준 1325번
https://www.acmicpc.net/problem/1325
import sys
from collections import deque
input = sys.stdin.readline
N, M = map(int, input().split())
A = [[] for _ in range(N + 1)]
answer = [0] * (N + 1)
def BFS(v):
queue = deque()
queue.append(v)
visited[v] = True
while queue:
now_Node = queue.popleft()
for i in A[now_Node]:
if not visited[i]:
visited[i] = True
answer[i] += 1
queue.append(i)
for _ in range(M):
S, E = map(int, input().split())
A[S].append(E)
for i in range(1, N + 1):
visited = [False] * (N + 1)
BFS(i)
maxVal = 0
for i in range(1, N + 1):
maxVal = max(maxVal, answer[i])
for i in range(1, N + 1):
if maxVal == answer[i]:
print(i, end=' ')
백준 1707번
https://www.acmicpc.net/problem/1707
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
N = int(input())
IsEven = True
def DFS(node):
global IsEven
visited[node] = True
for i in A[node]:
if not visited[i]:
check[i] = (check[node]+1)%2
DFS(i)
elif check[node] == check[i]:
IsEven = False
for _ in range(N):
V, E = map(int, input().split())
A = [[] for _ in range(V+1)]
visited = [False]*(V+1)
check = [0]*(V+1)
IsEven = True
for i in range(E):
Start, End = map(int, input().split())
A[Start].append(End)
A[End].append(Start)
for i in range(1, V+1):
if IsEven:
DFS(i)
else:
break
if IsEven:
print("YES")
else:
print("NO")
백준 2251번
https://www.acmicpc.net/problem/2251
from collections import deque
Sender = [0, 0, 1, 1, 2, 2]
Receiver = [1, 2, 0, 2, 0, 1]
now = list(map(int, input().split()))
visited = [[False for j in range(201)] for i in range(201)]
answer = [False] * 201
def BFS():
queue = deque()
queue.append((0, 0))
visited[0][0] = True
answer[now[2]] = True
while queue:
now_Node = queue.popleft()
A = now_Node[0]
B = now_Node[1]
C = now[2] - A - B
for k in range(6):
next = [A, B, C]
next[Receiver[k]] += next[Sender[k]]
next[Sender[k]] = 0
if next[Receiver[k]] > now[Receiver[k]]:
next[Sender[k]] = next[Receiver[k]] - now[Receiver[k]]
next[Receiver[k]] = now[Receiver[k]]
if not visited[next[0]][next[1]]:
visited[next[0]][next[1]] = True
queue.append((next[0], next[1]))
if next[0] == 0:
answer[next[2]] = True
BFS()
for i in range(len(answer)):
if answer[i]:
print(i, end=' ')
지금까지 백준 알고리즘 그래프 1 부분이었습니다.
읽어주셔서 감사합니다. 😃