본문 바로가기

Algorithm

(C++) - 백준(BOJ) 2485번 : 가로수 답

반응형

최대공약수 문제입니다.


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
31
32
33
34
#include <iostream>
using namespace std;
int tree[100001];
int t[100001];
int n,ans;
int cmp = 100000001;
int m = 100000001;
int gcd(int a, int b)
{
    if (b == 0) { return a; }
    return gcd(b, a%b);
}
int main() {
    
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> tree[i];
 
        if (i >= 2)
        {
            t[i] = tree[i] - tree[i - 1]; //가로수 사이의 거리를 저장
            cmp = gcd(t[i], t[i - 1]);
        }
    
        if (m > cmp)//최대공약수 구하기
            m = cmp;
    }
    for (int i = 2; i <= n; i++)
    {
        ans += t[i] / m-1;
    }
    cout << ans << '\n';
}
cs