[백준] 17087번 - 숨바꼭질 6 [Java][C++]
[백준] 17087번 - 숨바꼭질 6 [Java][C++]
1. 문제 풀이
수빈이의 현재 위치에서 $D$ 만큼 이동할 수 있을 때, 모든 동생을 찾을 수 있는 $D$ 의 최댓값을 구하는 문제로 수빈이의 초기 위치와 동생들과의 위치의 차에 대한 최대공약수를 $D$ 로 설정하면 $D$ 의 배수만큼의 이동으로 모든 동생들을 찾을 수 있으면서 가능한 $D$ 가 최대가 된다.
절댓값을 활용해서 거리 기반으로 최대공약수를 계산했다.
2. 코드
1. 유클리드 호제법 [Java]
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 gcd = Math.abs(S - arr[0]);
for (int i = 1; i < N; i++) {
gcd = gcd(gcd, Math.abs(S - arr[i]));
}
System.out.println(gcd);
}
static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
}
2. 유클리드 호제법 [C++]
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(false);
cin.tie(nullptr);
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;
}
3. 풀이 정보
1. 유클리드 호제법 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 288 ms | 26032 KB | 839 B |
2. 유클리드 호제법 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 16 ms | 2412 KB | 324 B |
This post is licensed under CC BY 4.0 by the author.