Post

[BaekJoon] #17087 - 숨바꼭질 6 [Java][C++]

[BaekJoon] #17087 - 숨바꼭질 6 [Java][C++]

문제 링크


1. 아이디어

수빈이의 현재 위치에서 $D$만큼 이동할 수 있을 때, 모든 동생을 찾을 수 있는 $D$의 최댓값을 구하는 문제로 각 동생들과의 거리차가 전부 $D$의 배수이면 $D$만큼의 이동으로 모든 동생들을 찾을 수 있고, 하나라도 배수가 아니라면 그 동생은 찾을 수 없다. 이런 $D$의 최댓값을 구해야 하므로 모든 동생들과의 거리차의 최대공약수가 이런 조건을 만족하는 $D$가 된다.

절댓값을 활용해서 거리 기반으로 최대공약수를 계산했다.


2. 복잡도

접근시간공간
풀이$O(N \log M)$$O(N)$

($N$ = 입력값 n, $M$ = s와 동생 위치 사이 거리의 최댓값)


3. 코드

풀이 [Java][C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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 n = Integer.parseInt(st.nextToken());
        int s = Integer.parseInt(st.nextToken());

        int[] arr = new int[n];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        int g = Math.abs(s - arr[0]);
        for (int i = 1; i < n; i++) {
            g = gcd(g, Math.abs(s - arr[i]));
        }

        System.out.println(g);
    }

    static int gcd(int a, int b) {
        if (b == 0) return a;
        return gcd(b, a % b);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n, s;
    cin >> n >> s;

    vector<int> v(n);
    for (int& x : v) cin >> x;

    int g = abs(s - v[0]);
    for (int i = 1; i < n; i++) {
        g = gcd(g, abs(s - v[i]));
    }

    cout << g;
}

This post is licensed under CC BY 4.0 by the author.