
난이도: ★★★★☆ • solved on: 2025-07-09


int), 배열 (위치 추적)triangular number), 위치 패턴, 구현
- 문제 분해
- 시작을 1/1에서 시작, 대각선을 따라 지그재그로 움직임
- 방향 전환(↗, ↙)은 분자가 1이거나 분모가 1일 때 발생
- 반복문으로 한 칸씩 이동하며 N번째 위치에 도달할 때까지 수행
- 핵심 로직 흐름
axis = [1,1] for i in 1~N-1: if axis[0]==1 and isEdge: axis[1]+=1; isEdge=false; isUp = !isUp; continue if axis[1]==1 and isEdge: axis[0]+=1; isEdge=false; isUp = !isUp; continue if isUp: axis[0]-=1; axis[1]+=1; if(axis[0]==1) isEdge=true else: axis[0]+=1; axis[1]-=1; if(axis[1]==1) isEdge=true ``- 예외 처리
- N=1인 경우 1/1 바로 출력
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] axis = {1,1};
boolean isEdge = true;
boolean isUp = true;
if(n>1){
for(int i = 0; i < n-1; i++){
if(axis[0]==1&&isEdge){
axis[1]+=1;
isEdge = false;
isUp = !isUp;
continue;
}
if(axis[1]==1&&isEdge){
axis[0]+=1;
isEdge = false;
isUp = !isUp;
continue;
}
if(isUp){
axis[0]-=1;
axis[1]+=1;
if(axis[0]==1){
isEdge = true;
}
} else{
axis[0]+=1;
axis[1]-=1;
if(axis[1]==1){
isEdge = true;
}
}
}
}
System.out.println(axis[0]+"/"+axis[1]);
}
}
- 문제 분해
- 각 대각선(1, 2, 3, ...)에는 대각선 번호만큼의 원소가 들어감(1개, 2개, 3개 ...)
- N이 포함된 대각선 번호(
line)을 찾는다. (삼각수 공식 이용)line번째 대각선의 시작 위치 =(line-1)*line/2 + 1- 방향: line이 짝수면 (아래→위), 홀수면 (위→아래)
- 분자/분모는 line과 N의 상대적 위치로 바로 계산
- 핵심 로직 흐름
sum = 0, line = 0 while (sum < N): sum += ++line offset = N - (sum - line) if line % 2 == 0: 분자 = offset, 분모 = line - offset + 1 else: 분자 = line - offset + 1, 분모 = offset- 예외 처리
- N=1일 때 1/1 바로 출력
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int line = 0;
int sum = 0;
// N이 위치한 대각선(line) 찾기
while (sum < N) {
line++;
sum += line;
}
int offset = N - (sum - line); // 그 대각선에서 몇 번째인지
int numerator, denominator;
if (line % 2 == 0) {
numerator = offset;
denominator = line - offset + 1;
} else {
numerator = line - offset + 1;
denominator = offset;
}
System.out.println(numerator + "/" + denominator);
}
}
방법 1:
- 시간 복잡도 : O(N)
- 공간 복잡도 : O(1)
방법 2:
- 시간 복잡도 : O(√N) (대각선 번호 탐색)
- 공간 복잡도 : O(1)
비슷한 유형 (GPT 추천) :
확장 문제 (GPT 추천) :