본문 바로가기
Develop/Coding Test | Algorithm

[백준] JAVA 풀이 - 10811 : 바구니 뒤집기

by 코젼 2024. 2. 13.
728x90
반응형

 

▶️백준

https://www.acmicpc.net/problem/10811

 

10811번: 바구니 뒤집기

도현이는 바구니를 총 N개 가지고 있고, 각각의 바구니에는 1번부터 N번까지 번호가 순서대로 적혀져 있다. 바구니는 일렬로 놓여져 있고, 가장 왼쪽 바구니를 1번째 바구니, 그 다음 바구니를 2

www.acmicpc.net

 

▶️실패 답안

인텔리제이에서는 동작했지만 백준에서는 시간 복잡도를 고려하지 못해서 틀린 답안으로 제출되었다.

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 basketNum = Integer.parseInt(st.nextToken());
        int[] basket = new int[basketNum];
        int change = Integer.parseInt(st.nextToken());
        for (int i=0; i<basket.length; i++) basket[i] = i+1;
        for (int i=1; i<=change; i++) {
            st = new StringTokenizer(br.readLine());
            int first = Integer.parseInt(st.nextToken())-1;
            int last = Integer.parseInt(st.nextToken())-1;
            for (int j=first; j<=first+1; j++) {
                if (last == first) break;
                int temp = basket[j];
                basket[j] = basket[last];
                basket[last] = temp;
                last--;
            }
        }
        for (int i : basket) System.out.print(i + " ");
    }
}

 

▶️수정 답안

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 basketNum = Integer.parseInt(st.nextToken());
        int[] basket = new int[basketNum];
        int change = Integer.parseInt(st.nextToken());
        for (int i=0; i<basket.length; i++) basket[i] = i+1;
        for (int i=1; i<=change; i++) {
            st = new StringTokenizer(br.readLine());
            int first = Integer.parseInt(st.nextToken())-1;
            int last = Integer.parseInt(st.nextToken())-1;
            while (first < last) {
                int temp = basket[first];
                basket[first++] = basket[last];
                basket[last--] = temp;
            }
        }
        for (int i : basket) System.out.print(i + " ");
    }
}
728x90
반응형

댓글