본문 바로가기

알고리즘/백준

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

반응형

10811번 문제(1)
10811번 문제(2)

 

1. Scanner를 이용한 방법

import java.util.*;

public class Main{
    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);

        //바구니 개수
        int N = sc.nextInt();
        int M = sc.nextInt();

        int[] num = new int[N+1];

        for(int i=1; i<num.length; i++){
            num[i] = i;
        }
        
        for(int t=0; t<M; t++){
            int I = sc.nextInt();
            int J = sc.nextInt();

           for(int p=I; p<=J; p++){
                int temp = num[p];
                num[p] = num[J];
                num[J--] = temp;
           }
        }
        for(int k=1; k<num.length; k++){
            System.out.print(num[k] + " ");
        }
        sc.close();
    }
}

 

2. BufferedReader를 이용한 방법

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[] num = new int[N+1];

        for(int i=1; i<num.length; i++){
            num[i] = i;
        }
        
        for(int t=0; t<M; t++){
            
            StringTokenizer st2 = new StringTokenizer(br.readLine());
            int I = Integer.parseInt(st2.nextToken());
            int J = Integer.parseInt(st2.nextToken());

           for(int p=I; p<=J; p++){
                int temp = num[p];
                num[p] = num[J];
                num[J--] = temp;
           }

        }

        for(int k=1; k<num.length; k++){
            System.out.print(num[k] + " ");
        }

        br.close();
    }
}

 

이전에 해결했던 10813 - 공 바꾸기 문제를 참고하여서 풀면 된다.. 정렬 관련한 문제에 약해서 문제를 해결하는데 시간이 좀 오래 걸렸다...

 

[백준] 10813 - 공 바꾸기

반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 27866 - 문자와 문자열  (0) 2024.02.21
[백준] 1546 - 평균  (0) 2024.02.20
[백준] 3052 - 나머지  (0) 2024.02.18
[백준] 5597 - 과제 안 내신 분..?  (0) 2024.02.17
[백준] 10813 - 공 바꾸기  (0) 2024.02.16