한수는 크기가 2^N × 2^N인 2차원 배열을 Z모양으로 탐색하려고 한다. 예를 들어, 2×2배열을 왼쪽 위칸, 오른쪽 위칸, 왼쪽 아래칸, 오른쪽 아래칸 순서대로 방문하면 Z모양이다.
N > 1인 경우, 배열을 크기가 2^(N-1) × 2^(N-1)로 4등분 한 후에 재귀적으로 순서대로 방문한다.
다음 예는 2^2 × 2^2 크기의 배열을 방문한 순서이다.
N이 주어졌을 때, r행 c열을 몇 번째로 방문하는지 출력하는 프로그램을 작성하시오.
다음은 N=3일 때의 예이다.
첫째 줄에 정수 N, r, c가 주어진다.
r행 c열을 몇 번째로 방문했는지 출력한다.
1 ≤ N ≤ 15
0 ≤ r, c < 2N
2 3 1
11
3 7 7
63
1 0 0
0
4 7 7
63
10 511 511
262143
10 512 512
786432
문제 유형 : 분할 정복, 재귀
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int n = Integer.parseInt(st.nextToken());
int ty = Integer.parseInt(st.nextToken());
int tx = Integer.parseInt(st.nextToken());
System.out.println(recur(1<<n, ty, tx));
}
static int recur(int size, int y, int x){
if(size==0) return 0;
int half = size/2;
if(y<half && x<half) return recur(half, y, x);
else if(y<half && x>=half) return half*half + recur(half, y, x-half);
else if(y>=half && x<half) return 2*half*half + recur(half, y=half, x);
else return 3*half*half + recur(half, y-half, x-half);
}
}