๋ฐฑ์ค€ & ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/DFS & BFS

[๋ฐฑ์ค€ 2331] [dfs] ๋ฐ˜๋ณต์ˆ˜์—ด

_cactus 2021. 4. 22. 21:40
๋ฐ˜์‘ํ˜•

๐Ÿ’ป ๋ฐฑ์ค€ 2331๋ฒˆ [๋ฐ˜๋ณต์ˆ˜์—ด]

 

2331๋ฒˆ: ๋ฐ˜๋ณต์ˆ˜์—ด

์ฒซ์งธ ์ค„์— ๋ฐ˜๋ณต๋˜๋Š” ๋ถ€๋ถ„์„ ์ œ์™ธํ–ˆ์„ ๋•Œ, ์ˆ˜์—ด์— ๋‚จ๊ฒŒ ๋˜๋Š” ์ˆ˜๋“ค์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

www.acmicpc.net

ํ’€์ด)

์ฒซ๋ฒˆ์งธ ์ œ์ถœ : ๋Ÿฐํƒ€์ž„์—๋Ÿฌ(ModuleNotFoundError) ๋œธ

์•Œ๊ณ ๋ณด๋‹ˆ ๋ฐฑ์ค€์—์„œ๋Š” numpy๋ฅผ ๋ชป ์“ฐ๊ฒŒ ํ•จ...;;^^

# ์ฒซ๋ฒˆ์งธ
import numpy as np

a,p = map(int,input().split())
visited = {}
stack = []
def cal(a,p) :
    if a in visited :  
        return stack.pop() 
    else :
        visited[a] = 1
        stack.append(a)
        return cal(np.sum([int(i)**p for i in str(a)]),p)
dup_n = cal(a,p)
print(list(visited.keys()).index(np.sum([int(i)**p for i in str(dup_n)])))
# ==> ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ(ModuleNotFoundError) : numpy์—†๋Œ€...;;

 ๋‘๋ฒˆ์งธ ์ œ์ถœ

# ์ตœ์ข…์ œ์ถœ
a,p = map(int,input().split())
visited = {}
stack = []
def cal(a,p) :
    if a in visited :  
        return stack.pop() 
    else :
        visited[a] = 1
        stack.append(a)
        return cal(sum([int(i)**p for i in str(a)]),p)
dup_n = cal(a,p)
print(list(visited.keys()).index(sum([int(i)**p for i in str(dup_n)])))
# ==> ๋ฉ”๋ชจ๋ฆฌ : 28776K4B, ์‹œ๊ฐ„ : 64ms, ์ฝ”๋“œ๊ธธ์ด : 323B

 

dfs๋ฅผ ๊ณต๋ถ€ํ•  ๋•Œ ๋˜๋„๋ก์ด๋ฉด ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด๋ณด๋ ค๊ณ  ๋…ธ๋ ฅํ•จ

์œ„ ์ฝ”๋“œ์—์„œ๋Š” visited๋ฅผ dictionary๋กœ ์‚ฌ์šฉํ•˜์˜€๊ณ , stack๊ณผ ์žฌ๊ท€ํ•จ์ˆ˜ cal์„ ์‚ฌ์šฉํ•˜์˜€๋‹ค

728x90
๋ฐ˜์‘ํ˜•