알고리즘/백준
[Java] 백준 1074 Z
24시간이모자란
2023. 7. 4. 02:52
문제
1074번: Z
한수는 크기가 2N × 2N인 2차원 배열을 Z모양으로 탐색하려고 한다. 예를 들어, 2×2배열을 왼쪽 위칸, 오른쪽 위칸, 왼쪽 아래칸, 오른쪽 아래칸 순서대로 방문하면 Z모양이다. N > 1인 경우, 배열을
www.acmicpc.net
풀이
반복문으로 구현하였다.
풀이는 다음과 같다.
- 현재 size를 기준으로 (x,y) 가 몇 사분면에 위치하는지 체크한다.
- 정답 변수에 (사분면 * ( size/2 ) * (size/2) ) 을 누적합한다.
- 더 작은 단위로 쪼개기 위해 현재 (행, 열)에 모듈러 연산을 적용한다.
- 정답 변수를 출력한다.
코드
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Main m = new Main();
m.solution();
}
public void solution() throws IOException {
FastReader fr = new FastReader();
int N;
int r,c;
N = fr.nextInt();
r = fr.nextInt();
c = fr.nextInt();
int maxSize = Math.max(r,c);
long ans = 0;
int size = 1;
while( size <= maxSize){
size *= 2;
}
int d;
int quadrant;
while(size > 1){
d = size/2;
quadrant = (r / d) * 2 + (c / d);
ans += quadrant * d * d;
r %= d;
c %= d;
size /=2;
}
System.out.println(ans);
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}