๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 1697_์ˆจ๋ฐ”๊ผญ์งˆ

๋ฟŒ์•ผ._. 2022. 4. 5. 21:40

Silver I

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/1697)

<์ˆจ๋ฐ”๊ผญ์งˆ>

๋ฌธ์ œ 

 

์ˆ˜๋นˆ์ด๋Š” ๋™์ƒ๊ณผ ์ˆจ๋ฐ”๊ผญ์งˆ์„ ํ•˜๊ณ  ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ํ˜„์žฌ ์  N(0 ≤ N ≤ 100,000)์— ์žˆ๊ณ , ๋™์ƒ์€ ์  K(0 ≤ K ≤ 100,000)์— ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ๊ฑท๊ฑฐ๋‚˜ ์ˆœ๊ฐ„์ด๋™์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋งŒ์•ฝ, ์ˆ˜๋นˆ์ด์˜ ์œ„์น˜๊ฐ€ X์ผ ๋•Œ ๊ฑท๋Š”๋‹ค๋ฉด 1์ดˆ ํ›„์— X-1 ๋˜๋Š” X+1๋กœ ์ด๋™ํ•˜๊ฒŒ ๋œ๋‹ค. ์ˆœ๊ฐ„์ด๋™์„ ํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” 1์ดˆ ํ›„์— 2*X์˜ ์œ„์น˜๋กœ ์ด๋™ํ•˜๊ฒŒ ๋œ๋‹ค.

์ˆ˜๋นˆ์ด์™€ ๋™์ƒ์˜ ์œ„์น˜๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ˆ˜๋นˆ์ด๊ฐ€ ๋™์ƒ์„ ์ฐพ์„ ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ๋น ๋ฅธ ์‹œ๊ฐ„์ด ๋ช‡ ์ดˆ ํ›„์ธ์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

 

์ž…๋ ฅ

 

์ฒซ ๋ฒˆ์งธ ์ค„์— ์ˆ˜๋นˆ์ด๊ฐ€ ์žˆ๋Š” ์œ„์น˜ N๊ณผ ๋™์ƒ์ด ์žˆ๋Š” ์œ„์น˜ K๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. N๊ณผ K๋Š” ์ •์ˆ˜์ด๋‹ค.

 

 

์ถœ๋ ฅ 

 

์ˆ˜๋นˆ์ด๊ฐ€ ๋™์ƒ์„ ์ฐพ๋Š” ๊ฐ€์žฅ ๋น ๋ฅธ ์‹œ๊ฐ„์„ ์ถœ๋ ฅํ•œ๋‹ค.

 

 

๋ฌธ์ œ ํ’€์ด

   - my solution (Python)

import sys
from collections import deque

if __name__=='__main__':
    x,y=map(int,sys.stdin.readline().split())

    answer=[0]*100001 # ์‹œ๊ฐ„
    visited=[0]*100001 # ๋ฐฉ๋ฌธ ์—ฌ๋ถ€
    visited[x]=1
    queue=deque([x])

    dx=[-1,1,2]
    flag=0
    while queue:
        temp=queue.popleft()
        for i in range(2): # -1, +1
            x=temp+dx[i]
            if x>=0 and x<=100000 and visited[x]==0: # ๋ฒ”์œ„ ์•ˆ, ๋ฐฉ๋ฌธ x
                answer[x]=answer[temp]+1
                visited[x]=1 # ๋ฐฉ๋ฌธ
                queue.append(x)
                if x==y: # ๋™์ƒ์„ ์ฐพ์œผ๋ฉด
                    flag=1
                    break
        x=temp*2
        if x >= 0 and x <= 100000 and visited[x]==0: # ๋ฒ”์œ„ ์•ˆ, ๋ฐฉ๋ฌธ x
            answer[x] = answer[temp] + 1
            visited[x] = 1 # ๋ฐฉ๋ฌธ
            queue.append(x)
            if x==y or flag==1: # ๋™์ƒ์„ ์ฐพ์œผ๋ฉด
                break
    print(answer[y])

 

โ“ ์™œ ๋Ÿฐํƒ€์ž„ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋Š”๊ฐ€?

์ •๋ง ๋‹นํ™ฉ์Šค๋Ÿฝ๊ฒŒ๋„ 0 <= N <= 100,000 ์กฐ๊ฑด๊ณผ ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•˜์ง€ ์•Š์•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

๋ฌด์Šจ ์ƒ๊ฐ์œผ๋กœ ๊ทธ๋ƒฅ ํƒ์ƒ‰๋งŒ ํ–ˆ๋Š”์ง€ ๋ชจ๋ฅด๊ฒ ๋‹ค.

 

  • ์ˆ˜๋นˆ, ๋™์ƒ ์œ„์น˜ ์ž…๋ ฅ
  • answer = ์‹œ๊ฐ„
  • visited = ๋ฐฉ๋ฌธ ์—ฌ๋ถ€
  • queue๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต -> ์ œ์ผ ์ฒ˜์Œ ๊ฐ’์„ pop -> ์ด๋™ํ•˜๋ ค๋Š” ์œ„์น˜๊ฐ€ ๋ฒ”์œ„ ์•ˆ์ด๋ฉฐ ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด ์ดˆ ์ €์žฅ ๋ฐ ๋ฐฉ๋ฌธ check, queue์— ์ถ”๊ฐ€
    : ์ด๋™ํ•  ์œ„์น˜๊ฐ€ ๋™์ƒ์ด ์žˆ๋Š” ๊ณณ์ด๋ฉด ์ข…๋ฃŒ
    : x-1, x+1, x*2 ์ธ ๊ฒฝ์šฐ

 

โ“ java๋กœ๋„ ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ดค์ง€๋งŒ ๋˜‘๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜์˜€๋Š”๋ฐ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค. 

์•„์ง.... ์ด์œ ๋ฅผ ์ฐพ์ง€ ๋ชปํ•ด์„œ,....


์ƒ๊ฐ๐Ÿค”

 

java๋กœ๋Š” ์™œ ํ‹€๋ ธ์„๊นŒ,,?