본문 바로가기

알고리즘 공부/백준

17087번 숨바꼭질 6 with C++

문제

https://www.acmicpc.net/problem/17087

 

17087번: 숨바꼭질 6

수빈이는 동생 N명과 숨바꼭질을 하고 있다. 수빈이는 현재 점 S에 있고, 동생은 A1, A2, ..., AN에 있다. 수빈이는 걸어서 이동을 할 수 있다. 수빈이의 위치가 X일때 걷는다면 1초 후에 X+D나 X-D로 이

www.acmicpc.net

 

해결한 방법

1. 동생의 위치를 입력받을때마다 거리를 구한다.
2. 거리와 기존의 gcd값과 최대공약수를 구해서 gcd에 대입합니다.
3. 모든 거리와 계산했다면 gcd의 절대값을 출력합니다.
#include <iostream>
using namespace std;

int gcd(int a, int b) {
	int temp;
	while (b) {
		temp = b;
		b = a % b;
		a = temp;
	}
	return a;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);

	int N, S;
	cin >> N >> S;

	int position;
	int distance;
	int max_gcd;

	cin >> position;
	distance = S - position;
	max_gcd = distance;
	N--;

	while(N--){
		cin >> position;
		distance = S - position;
		max_gcd = gcd(max_gcd, distance);
	}
	
	cout << (max_gcd > 0 ? max_gcd : max_gcd * (-1));

	return 0;
}

 

'알고리즘 공부 > 백준' 카테고리의 다른 글

1212번 8진수 2진수 with C++  (0) 2022.07.13
1373번 2진수 8진수 with C++  (0) 2022.07.12
9613번 GCD 합 with C++  (0) 2022.07.12
2004번 조합 0의 개수 with C++  (0) 2022.07.12
1676번 팩토리얼 0의 개수 with C++  (0) 2022.07.11