[코드트리] X 달리기

h_jin·2025년 1월 10일

코테

목록 보기
8/33

문제링크

문제

달려가야할 거리 x가 주어지고
속력은 1로 시작하는데 도착 시 속력은 1이어야한다.
x까지 걸리는 최소 시간은?

풀이

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int speed = 1;
        int time = 0;
        int distance = 0;

        while (distance < n) {
            // 삼각수 계산 미리 저장
            int nextSpeedDistance = (speed + 1) * (speed + 2) / 2;
            int currentSpeedDistance = speed * (speed + 1) / 2;

            // 거리 증가 및 시간 증가
            distance += speed;
            time++;

            // 속도 조정
            if (distance + nextSpeedDistance <= n)
                speed++;
            else if (distance + currentSpeedDistance <= n)
                speed = speed;
            else
                speed--;
        }

        System.out.print(time);
    }
}
  • 속력을 높이고, 유지하고, 줄이는 기준을 세우는 것이 너무 어려웠음..
  • speed + 1에서 1까지의 총 합이 남은 거리보다 작거나 같다 => 속력 증가
  • speed에서 1까지의 총 합이 남은 거리보다 작거나 같다 => 속력 유지
  • 그렇지 않으면 속력 감소
  • 이렇게 했을때 최대로 속력을 낼 수 있어 최소 시간을 구할 수 있다.

0개의 댓글