πŸ“š Study/Baekjoon

[Silver IV] 2331 - λ°˜λ³΅μˆ˜μ—΄

윰갱 2025. 4. 10. 01:23

문제

λ‹€μŒκ³Ό 같이 μ •μ˜λœ μˆ˜μ—΄μ΄ μžˆλ‹€.

  • D[1] = A
  • D[n] = D[n-1]의 각 자리의 숫자λ₯Ό P번 κ³±ν•œ μˆ˜λ“€μ˜ ν•©

예λ₯Ό λ“€μ–΄ A=57, P=2일 λ•Œ, μˆ˜μ—΄ DλŠ” [57, 74(=52+72=25+49), 65, 61, 37, 58, 89, 145, 42, 20, 4, 16, 37, …]이 λœλ‹€. κ·Έ λ’€μ—λŠ” μ•žμ„œ λ‚˜μ˜¨ μˆ˜λ“€(57λΆ€ν„°κ°€ μ•„λ‹ˆλΌ 58λΆ€ν„°)이 λ°˜λ³΅λœλ‹€.

이와 같은 μˆ˜μ—΄μ„ 계속 κ΅¬ν•˜λ‹€ 보면 μ–Έμ  κ°€ 이와 같은 λ°˜λ³΅μˆ˜μ—΄μ΄ λœλ‹€. μ΄λ•Œ, λ°˜λ³΅λ˜λŠ” 뢀뢄을 μ œμ™Έν–ˆμ„ λ•Œ, μˆ˜μ—΄μ— λ‚¨κ²Œ λ˜λŠ” μˆ˜λ“€μ˜ 개수λ₯Ό κ΅¬ν•˜λŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜μ‹œμ˜€. μœ„μ˜ μ˜ˆμ—μ„œλŠ” [57, 74, 65, 61]의 λ„€ 개의 μˆ˜κ°€ λ‚¨κ²Œ λœλ‹€.

μž…λ ₯

첫째 쀄에 A(1 ≤ A ≤ 9999), P(1 ≤ P ≤ 5)κ°€ μ£Όμ–΄μ§„λ‹€.

좜λ ₯

첫째 쀄에 λ°˜λ³΅λ˜λŠ” 뢀뢄을 μ œμ™Έν–ˆμ„ λ•Œ, μˆ˜μ—΄μ— λ‚¨κ²Œ λ˜λŠ” μˆ˜λ“€μ˜ 개수λ₯Ό 좜λ ₯ν•œλ‹€.

예제 μž…λ ₯ 1

57 2

예제 좜λ ₯ 1

4

# 풀이 방법

μˆ˜μ—΄ > dfs μ ‘κ·Όν•˜λ €κ³  ν–ˆμœΌλ‚˜ ꡳ이 dfs둜 ν•  ν•„μš”κ°€ μžˆλ‚˜ ν•˜λŠ” 생각이 λ“€μ—ˆλ‹€.. 더 κ°„λ‹¨νžˆ ν•  수 μžˆμ„ 것 같은데

 

이 κ²½μš°μ—λŠ” graphλ₯Ό 전체 λ‹€ μž…λ ₯ λ°›κ³  ν•˜λ‚˜μ”© λ„λŠ”κ²Œ μ•„λ‹ˆλΌ λ…Έλ“œλ₯Ό μΆ”κ°€ν•˜λ©΄μ„œ 더 κ°ˆμ§€λ§μ§€ κ²°μ •ν•˜λŠ” λ°©λ²•μ΄μ—ˆλ‹€.

1. λ‹€μŒ λ…Έλ“œ 숫자 κ΅¬ν•˜κΈ°

2. λ‹€μŒ λ…Έλ“œ μˆ«μžκ°€ 이전에 있던 μˆ«μžμΈμ§€ κ΅¬ν•˜κΈ°

2-1. 이전에 있던 숫자라면, 인덱슀(λ‚¨κ²Œ λ˜λŠ” 수) 좜λ ₯

2-2.  이전에 μ—†λ˜ 숫자라면, 배열에 μΆ”κ°€ν•˜κ³  계속 μœ„μ˜ κ³Όμ • 반볡


# μ½”λ“œ

import sys
import math

sys.stdin = open("input.txt", "r")

A, P = map(int, sys.stdin.readline().split())
perm = [A]

def next(A):
    next_A = 0
    while A != 0:
        next_A += math.pow(A%10, P)
        A //= 10
    return next_A

while True:
    next_A = next(A)
    if next_A in perm:
        break
    perm.append(next_A)
    A = next_A
print(perm.index(next_A))

 


# μ°Έκ³ 

indexν•¨μˆ˜λ₯Ό μ“°λ©΄ 더 κ°„λ‹¨ν•˜λ‹€ μ•„λž˜λŠ” 볡작 ver

from collections import deque
import math
import sys
sys.stdin = open("input.txt","r")
a, p = map(int,sys.stdin.readline().split())
perm = []
perm.append(a)

def return_next(curr,p):
    next = 0
    while curr != 0:
        next += math.pow(curr%10,p)
        curr = curr // 10
    
    return int(next)

curr = a
while True:
    next = return_next(curr,p)
    if next not in perm:
        perm.append(next)
        curr = next
    else:
        for i in range(len(perm)):
            if perm[i] == next:
                break
        break

print(i)