본문 바로가기
알고리즘/[백준] JAVA

[백준] 10813 공 바꾸기

by 코딩맛집 2023. 4. 28.

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

 

10813번: 공 바꾸기

도현이는 바구니를 총 N개 가지고 있고, 각각의 바구니에는 1번부터 N번까지 번호가 매겨져 있다. 바구니에는 공이 1개씩 들어있고, 처음에는 바구니에 적혀있는 번호와 같은 번호가 적힌 공이

www.acmicpc.net

 

방법1

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

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

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

        int[] arr = new int[n];

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

        for(int i=0; i<m; i++){
            StringTokenizer str1 = new StringTokenizer(br.readLine());

            int num1 = Integer.parseInt(str1.nextToken());
            int num2 = Integer.parseInt(str1.nextToken());
            int temp = 0;

            temp = arr[num1-1];
            arr[num1-1] = arr[num2-1];
            arr[num2-1] = temp;

        }
        br.close();
        for(int number : arr){
            System.out.print(number + " ");
        }
    }
}

 

방법2

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

public class Main {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();

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

        for(int i=0; i<m; i++){
            int temp = 0;
            int num1 = sc.nextInt();
            int num2 = sc.nextInt();

            temp = arr[num1-1];
            arr[num1-1] = arr[num2-1];
            arr[num2-1] = temp;
        }
        sc.close();
        for(int j=0; j<arr.length; j++){
            System.out.print(arr[j] + " ");
        }
    }
}

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

[백준] 10811 바구니 뒤집기  (0) 2023.05.02
[백준] 3052 나머지  (0) 2023.05.02
[백준] 2562 최댓값  (0) 2023.04.28
[백준] 10818 최소, 최대  (0) 2023.04.25
[백준] 10807 개수 세기  (0) 2023.04.25