[백준 16953] A->B

2024. 8. 22. 01:05·Study/Algorithm
728x90

백준 16953 A -> B

접근

  • 처음에는 이진 트리로 1차원 배열에 두 연산을 저장하면서 진행하려고 했으나 메모리 초과가 발생한다는 것을 깨닫고 방향을 전환하였다.
  • BFS 를 통해서 B까지 도달할 수 있는 가능한 연산 횟숫를 찾고자 하였다.
  • 만약 가능한 연산이 없을 경우에는 -1을 출력해야 한다.

전체 코드


import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int A = Integer.parseInt(st.nextToken());
        int B = Integer.parseInt(st.nextToken());
        Queue<long[]> queue = new LinkedList<>();
        queue.add(new long[] { A, 1 }); 

        while (!queue.isEmpty()) {
            long[] current = queue.poll();
            long value = current[0];
            long operations = current[1];

            if (value == B) {
                System.out.println(operations);
                return;
            }

            if (value * 2 <= B) {
                queue.add(new long[] { value * 2, operations + 1 });
            }

            if (value * 10 + 1 <= B) {
                queue.add(new long[] { value * 10 + 1, operations + 1 });
            }
        }
        System.out.println(-1);
    }

}
728x90
반응형
저작자표시 (새창열림)

'Study > Algorithm' 카테고리의 다른 글

[백준 1238] 파티  (0) 2024.08.25
[백준 1167] 트리의 지름  (0) 2024.08.23
[백준 11660] 구간 합 구하기 5  (2) 2024.08.21
[baekjoon] 세탁소 사장 동혁(2720)  (0) 2024.05.31
[SWEA] 5658. [모의 SW 역량테스트] 보물상자 비밀번호  (1) 2024.05.18
'Study/Algorithm' 카테고리의 다른 글
  • [백준 1238] 파티
  • [백준 1167] 트리의 지름
  • [백준 11660] 구간 합 구하기 5
  • [baekjoon] 세탁소 사장 동혁(2720)
pink_salt
pink_salt
유익함을 주는 개발자가 되도록 keep going
  • pink_salt
    KeepGoingForever
    pink_salt
  • 전체
    오늘
    어제
    • 분류 전체보기 (117)
      • Project (7)
      • WEB study (3)
        • WEB(Springboot) (10)
        • Git, GitLab (13)
        • Clean code (1)
        • FrontEnd (3)
      • Study (21)
        • Algorithm (19)
        • 면접 준비 (2)
      • Cloud Computing (2)
        • AWS (2)
      • 프로그래밍 언어 (35)
        • Java (29)
        • Python (0)
        • javascript (6)
      • 운영체제 (0)
        • Linux (0)
      • Database (4)
        • MongoDB (8)
        • SQL (8)
      • 애플리케이션 개발 (1)
        • Android (1)
      • AI (1)
        • Deeplearning (1)
        • machinelearning (0)
      • Daily (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    BFS
    codepresso
    Query
    gitlab
    언어
    코드프레소
    코딩이러닝
    spring boot
    빅오표기법
    코딩강의
    git branch
    개념
    무료IT교육
    무료코딩교육
    Java
    Git
    dp
    MongoDB
    대외활동
    자바
    백준
    SWEA
    Database
    python
    mysql
    티스토리챌린지
    오블완
    객체지향
    IT교육
    SW
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
pink_salt
[백준 16953] A->B
상단으로

티스토리툴바