한수는 크기가 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 < 2^N
예제 입력 1
2 3 1 |
예제 출력 1
11 |
예제 입력 2
3 7 7 |
예제 출력 2
63 |
예제 입력 3
1 0 0 |
예제 출력 3
0 |
예제 입력 4
4 7 7 |
예제 출력 4
63 |
예제 입력 5
10 511 511 |
예제 출력 5
262143 |
예제 입력 6
10 512 512 |
예제 출력 6
786432 |
더보기
Solution
#include<stdio.h>
int main(void)
{
int N, r, c, x=0, y=0, order=0;
scanf("%d%d%d", &N, &r, &c);
N--;
while(x!=r || y!=c)
{
int shift=1<<N;
if(x+shift<=r && y+shift<=c)
{
order+=3*shift*shift;
x+=shift;
y+=shift;
}
else if(x+shift<=r)
{
order+=2*shift*shift;
x+=shift;
}
else if(y+shift<=c)
{
order+=shift*shift;
y+=shift;
}
N--;
}
printf("%d\n", order);
return 0;
}
더보기
Solution
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
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 r=Integer.parseInt(st.nextToken());
int c=Integer.parseInt(st.nextToken());
int x=0, y=0, order=0;
N--;
while(x!=r || y!=c) {
int shift=1<<N;
if(x+shift<=r && y+shift<=c) {
order+=3*shift*shift;
x+=shift;
y+=shift;
}
else if(x+shift<=r) {
order+=2*shift*shift;
x+=shift;
}
else if(y+shift<=c) {
order+=shift*shift;
y+=shift;
}
N--;
}
System.out.println(order);
}
}
728x90
'백준 알고리즘' 카테고리의 다른 글
<백준 알고리즘> 17299번: 오등큰수 (0) | 2023.02.21 |
---|---|
<백준 알고리즘> 6198번: 옥상 정원 꾸미기 (0) | 2023.02.21 |
<백준 알고리즘> 1992번: 쿼드트리 (0) | 2023.02.20 |
<백준 알고리즘> 2630번: 색종이 만들기 (0) | 2023.02.20 |
<백준 알고리즘> 14502번: 연구소 (0) | 2023.02.20 |