본문 바로가기

Coding Test/백준

[백준/자바] 10811 - 바구니 뒤집기

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());

        int[] balls = new int[n];
        for(int i=0; i<n; i++){
            balls[i] = i + 1;
        }

        for(int i=0; i<m; i++){
            st = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(st.nextToken()) - 1;
            int b = Integer.parseInt(st.nextToken()) - 1;

            if(b - a < 3){
                int temp = balls[a];
                balls[a] = balls[b];
                balls[b] = temp;
            } else {
                int j = 0;
                while(a + j < b - j){
                    int temp = balls[a + j];
                    balls[a + j] = balls[b - j];
                    balls[b - j] = temp;
                    j++;
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        for(int ball : balls){
            sb.append(ball + " ");
        }

        System.out.println(sb);

        br.close();
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());

        int[] balls = new int[n];
        for(int i=0; i<n; i++){
            balls[i] = i + 1;
        }

        for(int i=0; i<m; i++){
            st = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(st.nextToken()) - 1;
            int b = Integer.parseInt(st.nextToken()) - 1;

            while(a < b){
                int temp = balls[a];
                balls[a++] = balls[b];
                balls[b--] = temp;
            }
        }

        for(int ball : balls){
            System.out.print(ball + " ");
        }

        br.close();
    }
}

  

위의 답안을 좀더 간단하게 바꾼 버전

if, else 문을 없애고, StringBuilder 대신 System.out.print()로 출력한다.