(JAVA) 백준온라인 17087번 - 숨바꼭질 6

2023. 8. 17. 11:37백준온라인

이 문제를 읽고 이해가 안 됐었다 .. 나만 그런가 해서 구글링을 해서 다른 분들의 글을 보았더니 나만 그렇게 생각했던건 아니었다! 휴

간단하게 D란? 수빈이가 한번에 걸을 수 있는 보폭의 크기다!

이것을 최대공약수 알고리즘인 gcd알고리즘을 사용하는 것이다

수빈이와 동생 N명의 각각 거리를 구한 다음 그 각각의 거리들의 최대 공약수를 구하면 된다!

a, b, c가 있고 이 세 수의 최대 공약수를 구하고 싶다면 a와 b의 최대공약수를 구하고 그 최대 공약수와 c간의 최대 공약수를 구하면 된다

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] info = br.readLine().split(" ");
        // info[0]에 N입력 / info[1]에 S
        String[] temp = br.readLine().split(" ");

        int[] distance = new int[temp.length];

        for(int i = 0; i<temp.length; i++){
            if(Integer.parseInt(temp[i])> Integer.parseInt(info[1])){
                distance[i] = Integer.parseInt(temp[i]) - Integer.parseInt(info[1]);
            }else{
                distance[i] = Integer.parseInt(info[1]) - Integer.parseInt(temp[i]);
            }
        }

        int brother = Integer.parseInt(info[0]);

        int answer = distance[0];

        if(brother != 1){
            //동생이 한명이 아닐 경우 최대 공약수 구하기
            for(int i= 1; i<distance.length; i++){
                answer = gcd(answer,distance[i]);
            }
        }
        System.out.println(answer);
    }

    public static int gcd(int x, int y) {
        int a = x % y;

        if (a == 0) {
            return y;
        } else {
            return gcd(y, a);
        }
    }
}

잘 모르겠는 부분은 계속 다른 분들의 코드를 보면서 작성하였는데 이렇게 공부하는 것이 맞는 방법인지 모르겠다 ㅎㅎ

가끔은 거의 다 베끼는 수준으로 참고를 하는데 옳은 방법인지 생각을 많이 해봐야겠다