[BOJ] 10813 - 공 바꾸기 (Java)

EunBeen Noh·2023년 11월 15일

Algorithm

목록 보기
12/52

알고리즘

  • 구현
  • 시뮬레이션

1. 문제

2. Idea

  • 배열 index = 바구니 번호
  • 배열 요소 = 바구니에 들어있는 공 번호

3. 풀이

3.1. 변수 선언 및 초기화

  • N: 바구니 수
  • M: 공 바꾸기 횟수
  • buckets[i]=k -> i번 바구니에는 k번 공이 들어있다.
  • 인덱스를 활용하기 위해 배열의 크기는 N+1
private static int N;
private static int M;
private static int[] buckets;
buckets=new int[N+1];

3.1. 입력을 배열에 저장

for(int i=0; i<=N; i++){buckets[i]=i;}

3.2. 공 바꾸기 수행

  • 각 입력줄의 바구니 번호(index)에 담긴 내용 교환
for(int i=0; i<M; i++){
	st=new StringTokenizer(sc.nextLine());
    int num1=Integer.parseInt(st.nextToken());
    int num2=Integer.parseInt(st.nextToken());
    int ball1=buckets[num1];
    int ball2=buckets[num2];
    buckets[num1]=ball2;
    buckets[num2]=ball1;
}

3.3. 결과 출력

  • 각 바구니에 담긴 공 번호 출력
for(int i=1; i<=N; i++){System.out.print(buckets[i]+" ");}


## 4. 전체코드

```java
package week5;
//Bronze_공 바꾸기 *
import java.util.*;
public class BOJ_10813 {
    private static int N;
    private static int M;
    private static int[] buckets;
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        StringTokenizer st=new StringTokenizer(sc.nextLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

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

        for(int i=0; i<M; i++){
            st=new StringTokenizer(sc.nextLine());
            int num1=Integer.parseInt(st.nextToken());
            int num2=Integer.parseInt(st.nextToken());
            int ball1=buckets[num1];
            int ball2=buckets[num2];
            buckets[num1]=ball2;
            buckets[num2]=ball1;
        }

        for(int i=1; i<=N; i++){System.out.print(buckets[i]+" ");}
    }
}

0개의 댓글