π§ κΉμ΄ μ°μ νμ, DFS (Depth First Search)
https://chan4im.tistory.com/121
π§ λ°±μ€ 2023 (DFS) Gold V
π€ Algorithm κ³Όμ
1. νμ리μμ -> μ΄ νμ리 μμμμ νμλμ΄ λμ¨ λμ리μμ -> ... μ λ°λ³΅μ΄λ―λ‘
2. νμ리 μμλ [2, 3, 5, 7]μ΄λ€.
3. μ¬κΈ°μ νμλλ μμλ λ€μκ³Ό κ°λ€.
[2] - 23, 29
[3] - 31, 37
[5] - 53, 59
[7] - 71, 73, 79
μ κ³Όμ μ κ³μ λ°λ³΅νμ¬ μ λ ₯λ μ리μμ λ§λ μΆλ ₯μ μ§νν΄μ£Όλ©΄ λλ€.
μ΄λ μ¬κ·λ₯Ό μ΄μ©ν DFSλ₯Ό ν΅ν΄ ν΄κ²°ν μ μμΌλ©° μλ κ·Έλ¦Όμ ν΅ν΄ κ°λ¨ν λμν νμλ€.
π€« solution_2023 (μκ°μ΄κ³Ό)import sys, math sys.setrecursionlimit(10000) input = sys.stdin.readline N = int(input()) dec = [i for i in range(2, 8*10**(N))] dec_front = [] for i in range(2, int(math.sqrt(10**(N+1))) + 1): if i in dec: dec_front.append(i) dec = [j for j in dec if j % i != 0] decimal = dec_front + dec single_decimal = [2, 3, 5, 7] def DFS(num): if len(str(num)) == N: print(num) else: for i in range(1, 10, 2): if num*10 + i in decimal: DFS(num*10 + i) for i in single_decimal: DFS(i)
π€« solution_2023
import sys sys.setrecursionlimit(10000) input = sys.stdin.readline N = int(input()) single_decimal = [2, 3, 5, 7] def decimal(num): for i in range(2, num//2 + 1): if num % i == 0: return False return True def DFS(num): if len(str(num)) == N: print(num) else: for i in range(1, 10, 2): if decimal(num*10 + i): DFS(num*10 + i) for i in single_decimal: DFS(i)
cf. // λ μ μν λλμ μ΄λ€.
π§ λ°±μ€ 13023 (DFS) Gold V
π€ Algorithm κ³Όμ
1. κ·Έλνλ₯Ό μΈμ 리μ€νΈλ‘ μ μ₯νλ€. (무방ν₯ κ·Έλνμ΄κΈ°μ μμͺ½λ°©ν₯μΌλ‘ κ°μ μ λͺ¨λ μ μ₯νλ€.)
2. 방문리μ€νΈλ₯Ό λͺ¨λ Falseλ‘ μ΄κΈ°ννλ€.
3. DFSλ₯Ό μννλλ°, μλμ κ°μ΄ μ§ννλ€.
4. μ΅μ’ μ μΌλ‘ DFSμ μ¬κ· νμκ° 5ν μ΄μμ΄λ©΄ λλ―λ‘ 5νκ° λ μκ°μ΄ λ°λ‘ μκ³μ μ΄λ€.
5. λ°λΌμ μ¬κ·νμκ° 5νλ©΄ λ°λ‘ 1μ μΆλ ₯νκ³ 5ν λ―Έλ§μ΄λΌλ©΄ 0μ μΆλ ₯νλ€.
π€« solution_13023# λ°±μ€ 11724 # μΉκ΅¬ κ΄κ³ 5κ°λ₯Ό μ°Ύλ λ¬Έμ = μ¬κ· κΉμ΄κ° 5λ² μ΄μμ΄λ©΄ λλ€. import sys input = sys.stdin.readline V, m = map(int, input().split()) vertex = [[] for _ in range(V+1)] # λ°©λ¬Έ 리μ€νΈ μμ± visit_list = [False] * (V+1) for _ in range(m): u, v = map(int, input().split()) vertex[u].append(v) vertex[v].append(u) # print(vertex) => [[1], [0, 2], [1, 3], [2, 4], [3], []] # μΈμ 리μ€νΈ μμ± [0] [1] [2] [3] [4] threshold = False def DFS(curr_vertex, depth): global threshold if depth == 5: threshold = True return visit_list[curr_vertex] = True for i in vertex[curr_vertex]: if not visit_list[i]: DFS(i, depth+1) visit_list[curr_vertex] = False for i in range(V): DFS(i, 1) if threshold: break if threshold: print(1) else: print(0)