ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [백준/C] 1193번 - 분수 찾기
    Problem Solving 2022. 5. 12. 18:40

    문제는 위와 같다.

     

    풀이를 위해 접근한 방법은 다음과 같다.

     

    1. 지그재그로 진행하며 같은 선 위에 위치하는 분수는 1번 / 2, 3번 / 4, 5, 6번 / ... 이다. 각각을 1번 cycle, 2번 cycle, 3번 cycle, ... 로 보자.

    2. 배열 위에서 홀수 cycle에서는 번호가 우상향으로 진행한다. 반면, 짝수 cycle에서는 좌하향으로 진행한다.

    3. 따라서, X가 몇 번째 cycle에 속하는지 구하면 진행 방향을 알 수 있다.

    4. 이어서 이전 cycle 까지 번호의 수를 X에서 빼주면 X가 몇 번째인지 알 수 있다.

    5. X가 속한 cycle number와 cycle 내 X의 order를 이용해 해당 분수를 계산한다.

     

    #include <stdio.h>
    
    int main(){
        int X, to_get_order=0, cycle=1, prev_cycle_num, order_in_cycle;
        scanf("%d", &X);
        
        // X가 속한 cycle
        while(1){
            to_get_order = to_get_order + cycle; // 1, 3, 6, 10, ...
            if(X <= to_get_order){
                break;
            }
            cycle++;
        }
        
        // X가 속한 cycle의 이전 cycle의 번호 수
        prev_cycle_num = to_get_order - cycle;
        
        // X가 속한 cycle 내 X의 order
        order_in_cycle = X - prev_cycle_num;
        
        // 분수 계산 및 출력
        if(cycle%2==0){
            printf("%d/%d\n", order_in_cycle, cycle - (order_in_cycle - 1));
        } else {
            printf("%d/%d\n", cycle - (order_in_cycle - 1), order_in_cycle);
        }
        
        return 0;
    }

     

    변수 네이밍이 너무 어렵다... 주석 없이도 쉽게 이해 될 정도로 만든다는게 꽤 신경을 써야 하는 일인 것 같다.

Designed by Tistory.