1. 문제

2485번: 가로수



2. 개요

직선 도로 위에 가로수들이 심어져 있다.

가로수들이 모두 같은 간격이 되도록 나무를 추가로 심으려고 한다.

새로 심는 나무는 항상 이미 심어져 있는 나무들 사이에 심어져야 한다.

이 때, 추가되는 나무의 최소 개수를 구하는 문제.



3. 풀이 및 코드

3-1. 풀이

나무들간의 거리가 현재 인접한 나무들간의 거리의 최대공약수가 되도록 나무를 심으면 된다.

따라서 인접한 나무들의 거리들을 구한 후, 최대공약수를 구한다.

이미 심어진 나무들을 탐색하면서 인접한 나무의 거리 / 최대공약수 - 1을 답에 더해준다.

모든 탐색이 끝났다면 답을 출력한다.

3-2. Python

import sys
import math

trees = []
nums = []

N = int(sys.stdin.readline())

for i in range(N):
    trees.append(int(sys.stdin.readline()))

    if i > 0:
        nums.append(trees[i] - trees[i - 1])

gcd = math.gcd(*nums)
answer = 0

for i in range(1, N):
    answer += (trees[i] - trees[i-1]) // gcd - 1

print(answer)

3-3. C#

namespace boj_2485
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int N = int.Parse(Console.ReadLine());

            int[] trees = new int[N];
            int[] nums = new int[N-1];

            for (int i = 0; i < N; i++)
            {
                trees[i] = int.Parse(Console.ReadLine());

                if (i > 0)
                    nums[i - 1] = trees[i] - trees[i - 1];
            }

            int gcd = GCD(nums);
            int answer = 0;

            for (int i = 1; i < N; i++)
            {
                answer += (trees[i] - trees[i - 1]) / gcd - 1;
            }

            Console.WriteLine(answer);
        }

        static int GCD(int first, int second)
        {
            while (first != 0 && second != 0)
            {
                if (first > second)
                    first %= second;
                else
                    second %= first;
            }

            return first == 0 ? second : first;
        }

        static int GCD(int[] nums)
        {
            if (nums.Length == 0)
                return 0;

            int result = nums[0];

            for (int i = 0; i < nums.Length; i++)
            {
                result = GCD(result, nums[i]);
            }

            return result;
        }
    }
}

.

Comments