21.06.01 기록

최대 1 분 소요

  • 백준 알고리즘 1193 풀이 완료

    • 내가 푼 1193 풀이(메모리 15.2MB, 시간 156ms로 통과)
      그냥 System.out.println으로 출력하는 것보다 StringBuilder를 한 번 거친 후 출력하는 것이 조금 더 빨랐다.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class B1193 {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringBuilder sb = new StringBuilder();
            int X = Integer.parseInt(br.readLine());
    
            if(X == 1) {
                sb.append(1).append("/").append(1);
                System.out.println(sb);
                return;
            }
    
            int round = 2;
            int count = 1;
    
            while(true) {
                for(int i = 1; i <= round; i++) {
                    count++;
                    if(count == X) {
                        sb.append(i).append("/").append(round-i+1);
                        System.out.println(sb);
                        return;
                    }
                }
                round++;
    
                for(int i = round; i > 0; i--) {
                    count++;
                    if(count == X) {
                        sb.append(i).append("/").append(round-i+1);
                        System.out.println(sb);
                        return;
                    }
                }
                round++;
            }
        }
    }
    


    • 해설 풀이(메모리 14.1MB, 시간 128ms로 통과)
      X가 배열의 누적 칸 수(prevCountSum)와 대각선의 수(crossCount)의 합보다 작거나 같을 때까지 첫번째 if-else 구문의 else 구문을 수행한다.
      X가 첫번째 if문을 만족할 때 대각선의 수의 홀/짝에 따라 두번째 if문을 수행한다.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class B1193 {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringBuilder sb = new StringBuilder();
    
            int X = Integer.parseInt(br.readLine());
            int prevCountSum = 0;
            int crossCount = 1;
    
            while(true) {
                if(X <= (prevCountSum + crossCount)) {
    
                    if(crossCount % 2 == 1) {
                        sb.append(crossCount - (X - prevCountSum - 1)).append("/").append(X - prevCountSum);
                        System.out.println(sb);
                        break;
                    } else {
                        sb.append(X - prevCountSum).append("/").append(crossCount - (X - prevCountSum - 1));
                        System.out.println(sb);
                        break;
                    }
    
                } else {
                    prevCountSum += crossCount;
                    crossCount++;
                }
            }
        }
    }
    


카테고리:

업데이트: