코딩테스트/백준

[백준 JAVA] 23970. 알고리즘 수업 - 버블 정렬 3

tkxx_ls 2024. 8. 20. 11:01

문제 링크


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

접근 방법


배열 A와 B가 같은지 확인하는 횟수를 최대한 적게 합니다.

소스 코드


import java.util.*;
import java.io.*;

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

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        String[] tmp = br.readLine().split(" ");
        int[] a = Arrays.stream(tmp).mapToInt(Integer::parseInt).toArray();
        tmp = br.readLine().split(" ");
        int[] b = Arrays.stream(tmp).mapToInt(Integer::parseInt).toArray();

        if (Arrays.equals(a, b)) {
            System.out.println(1);
            return;
        }

        // boolean flag;
        for (int i = n - 1; i >= 1; i--) {
            // flag = true;
            for (int j = 0; j < i; j++) {
                if (a[j] > a[j + 1]) {
                    // flag = false;
                    int t = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = t;
                    if (a[j] == b[j] && a[j + 1] == b[j + 1] && Arrays.equals(a, b)) {
                        System.out.println(1);
                        return;
                    }
                }
            }

            // if (flag) {
            //     break;
            // }
        }

        System.out.println(0);
    }
}

코드 설명


먼지 배열 2개가 같은지 확인합니다.

다르다면 버블 정렬에서 교환이 일어날 때, 교환한 값이 b배열과 같다면 배열 전체가 같은지 확인합니다.