1074번 Z

2024. 4. 22. 20:22백준

1074 Z //백준
한수는 크기가 2N × 2N
인 2차원 배열을 Z모양으로 탐색하려고 한다. 예를 들어, 2×2배열을 왼쪽 위칸, 오른쪽 위칸, 왼쪽 아래칸, 오른쪽 아래칸 순서대로 방문하면 Z모양이다.

N > 1인 경우, 배열을 크기가 2N-1 × 2N-1로 4등분 한 후에 재귀적으로 순서대로 방문한다.
다음 예는 22 × 22 크기의 배열을 방문한 순서이다.



N이 주어졌을 때, r행 c열을 몇 번째로 방문하는지 출력하는 프로그램을 작성하시오.
다음은 N=3일 때의 예이다.

● 풀이법
자료
자료의 풀이를 이용했다. 4분면으로 나누어 계산하는것 하는 도중 "<<" 문의 존제를 알게 되었다.
"<<"(비트 쉬프드)
  • 정답
더보기
package org.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main{
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String input[] = bf.readLine().split(" ");
        int n = Integer.parseInt(input[0]);
        int r = Integer.parseInt(input[1]);
        int c = Integer.parseInt(input[2]);

        long index = 0;

        while (n > 0) {
            long temp = 1L << (n - 1);
            if (r < temp && c >= temp) {
                index += temp * temp;
                c -= temp;
            }else if (r >= temp && c < temp){
                index += 2 * temp * temp;
                r -= temp;
            }else if (r >= temp && c >= temp){
                index += 3 * temp * temp;
                r -= temp;
                c -= temp;
            }
            n--;
        }
        System.out.println(index);

    }
}

'백준' 카테고리의 다른 글

10811번 바구니 뒤집기  (0) 2024.04.23
2908번 상수  (0) 2024.04.23
1920번 수 찾기  (0) 2024.04.19
11050번 이항 계수 1  (1) 2024.04.19
10814번 나이순 정렬  (0) 2024.04.19