백준1011. Fly me to the Alpha Centauri

김태훈·2024년 1월 8일
0

알고리즘

목록 보기
1/7

백준 1011. Fly me to the Alpha Centauri

출발지점과 도착지점을 입력받아 도착지점까지 도달하는데 걸리는 횟수를 구하는 문제입니다.
한 번 이동할 때마다, 현재 이동거리의 -1, 0, 1 만큼 더해서 이동할 수 있으며 최소한의 이동거리를 구해야 합니다.

거리가 제곱의 수 1, 4, 9일 때, 1, 121, 12321 식으로 진행됩니다.
즉 최대 이동거리는, 소숫점 버린, 루트 행선간 거리입니다.
이동 횟수는 최대이동 횟수의 max 2 - 1, max 2, max * 2 + 1인데
max×21max \times 2 - 1거리\sqrt{거리} = maxmax
max×2max \times 2거리\sqrt{거리} <= max×max+maxmax \times max + max
max×2+1max \times 2 + 1는 그 외입니다.

import java.util.Scanner;

public class Main{

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();	//테스트 케이스

        for(int i=0;i<T;i++) {
            int x = sc.nextInt();
            int y = sc.nextInt();

            int dist = y - x;	//행성간 거리
            int cnt = 0;		//이동 횟수

            int max = (int)Math.sqrt(dist);	//최대 이동 거리

            if(max == Math.sqrt(dist)) {
                System.out.println(max * 2 - 1);
            }
            else if(dist <= max * max + max) {
                System.out.println(max * 2);
            }
            else {
                System.out.println(max * 2 + 1);
            }
        }
    }
}

0개의 댓글

관련 채용 정보