coding_test/BAEKJOON

백준 2209번 C언어 풀이

CodeJin 2021. 8. 19. 01:41

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

 

2292번: 벌집

위의 그림과 같이 육각형으로 이루어진 벌집이 있다. 그림에서 보는 바와 같이 중앙의 방 1부터 시작해서 이웃하는 방에 돌아가면서 1씩 증가하는 번호를 주소로 매길 수 있다. 숫자 N이 주어졌

www.acmicpc.net

숫자가 새겨진 벌집모양의 방에서 1번방에서 N번방까지의 최소거리를 구하는 문제.

 

한 겹의 방 개수가 1, 6, 12, 18....인 점을 이용하여 문제를 풀고자 한다.

 

어디서 틀린지 잘 모르겠다.

#include <stdio.h>

int geometric_sum (int a, int end) { // 밑, 더하는 지수 범위
    int result = 1;
    int temp = 6;

    for (int i = 1; i < end; i++) {
        result += temp;
        temp += a;
    }
    return result;
}

int main () {
    int result = 0;
    int N;

    scanf("%d", &N);

    while (1) {
        if (N == 1) break;
        if (geometric_sum(6, result) <= N && geometric_sum(6, result+1) > N) {
            break;
        } else {
            result++;
        }
    }
    printf("%d", result + 1);
}

 -------------------------21.08.19----------------------------------

 

난 왜 이걸 등비수열로 봤는지 모르겠다.

 

한 레이어(?)당 숫자가 1, 6, 12, 18....개가 존재하는데, 첫째 항을 제외하면 등차수열이 된다. 따라서 이를 적용시키면 된다.

 

#include <stdio.h>

int arithmetic_sum (int d, int n) { // 공차, 더하는  범위
    int temp = 0;
    int result = 1;

    if (n != 1) {
        for (int i = 1; i < n; i++) {
            temp += d;
            result += temp;
        }
    }
    return result;
}

int main () {
    int result = 0;
    int N;

    scanf("%d", &N);

    while (1) {
        if (N == 1) break;
        if (arithmetic_sum(6, result) < N && arithmetic_sum(6, result+1) >= N) {
            break;
        } else {
            result++;
        }
    }
    printf("%d", result + 1);
}