오늘 풀어볼 문제는 백준 1517번 문제 "버블 소트" 이다.
이 문제는 플레티넘5 문제이고 버블 정렬 문제이다.
문제
N개의 수로 이루어진 수열 A[1], A[2], …, A[N]이 있다.
이 수열에 대해서 버블 소트를 수행할 때, Swap이 총 몇 번 발생하는지 알아내는 프로그램을 작성하시오.
버블 소트는 서로 인접해 있는 두 수를 바꿔가며 정렬하는 방법이다.
예를 들어 수열이 3 2 1 이었다고 하자.
이 경우에는 인접해 있는 3, 2가 바뀌어야 하므로 2 3 1 이 된다.
다음으로는 3, 1이 바뀌어야 하므로 2 1 3 이 된다.
다음에는 2, 1이 바뀌어야 하므로 1 2 3 이 된다. 그러면 더 이상 바꿔야 할 경우가 없으므로 정렬이 완료된다.
입력
첫째 줄에 N(1 ≤ N ≤ 500,000)이 주어진다.
다음 줄에는 N개의 정수로 A[1], A[2], …, A[N]이 주어진다.
각각의 A[i]는 0 ≤ |A[i]| ≤ 1,000,000,000의 범위에 들어있다.
출력
첫째 줄에 Swap 횟수를 출력한다.
📌첫 번째 도전📌
문제 자체는 버블 정렬이라고 기재되어 있지만, 실제 버블 정렬로 풀면 시간 초과가 뜰 가능성이 크다. 그래서 병합 정렬을 활용했다. 앞 글에서 이미 병합 정렬로 문제를 풀었기에 코드 구현은 복사 붙여넣기로 금방했다. 추가한 내용은 swap 횟수를 세는 코드만 추가했다.
public class Main {
static int[] arr;
static int[] tmp;
static int count;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(st.nextToken());
arr = new int[N+1];
tmp = new int[N+1];
st = new StringTokenizer(br.readLine());
for(int i=1; i<=N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
count = 0;
merge_sort(1, N);
System.out.println(count);
}
private static void merge_sort(int start, int end) {
if (end - start < 1) {
return;
}
int m = start + (end - start) / 2;
merge_sort(start, m);
merge_sort(m+1, end);
for(int i = start; i <= end; i++) {
tmp[i] = arr[i];
}
int k = start;
int index1 = start;
int index2 = m + 1;
while (index1 <= m && index2 <= end) {
if(tmp[index1] > tmp[index2]) {
arr[k] = tmp[index2];
count = count + index2 - k;
k++;
index2++;
} else {
arr[k] = tmp[index1];
k++;
index1++;
}
}
while (index1 <= m) {
arr[k] = tmp[index1];
k++;
index1++;
}
while (index2 <= end) {
arr[k] = tmp[index2];
k++;
index2++;
}
}
}
그런데.. 틀렸다고 한다. 왜지??
📌두 번째 도전📌
BufferWriter로 코드를 수정해보았다. 틀렸다고 뜬 건 시간 초과가 아니라서 이 문제는 아닐텐데, 혹시나 하는 마음에 수정을 했다.
public class Main {
static int[] arr;
static int[] tmp;
static int count;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(st.nextToken());
arr = new int[N+1];
tmp = new int[N+1];
st = new StringTokenizer(br.readLine());
for(int i=1; i<=N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
count = 0;
merge_sort(1, N);
bw.write(count+"");
bw.flush();
bw.close();
}
private static void merge_sort(int start, int end) {
if (end - start < 1) {
return;
}
int m = start + (end - start) / 2;
merge_sort(start, m);
merge_sort(m+1, end);
for(int i = start; i <= end; i++) {
tmp[i] = arr[i];
}
int k = start;
int index1 = start;
int index2 = m + 1;
while (index1 <= m && index2 <= end) {
if(tmp[index1] > tmp[index2]) {
arr[k] = tmp[index2];
count = count + index2 - k;
k++;
index2++;
} else {
arr[k] = tmp[index1];
k++;
index1++;
}
}
while (index1 <= m) {
arr[k] = tmp[index1];
k++;
index1++;
}
while (index2 <= end) {
arr[k] = tmp[index2];
k++;
index2++;
}
}
}
또 틀렸다..
📌세 번째 도전📌
설마설마 하는 마음에 long count로 수정을 했다.
public class Main {
static int[] arr;
static int[] tmp;
static long count;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(st.nextToken());
arr = new int[N+1];
tmp = new int[N+1];
st = new StringTokenizer(br.readLine());
for(int i=1; i<=N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
count = 0;
merge_sort(1, N);
bw.write(count+"");
bw.flush();
bw.close();
}
private static void merge_sort(int start, int end) {
if (end - start < 1) {
return;
}
int m = start + (end - start) / 2;
merge_sort(start, m);
merge_sort(m+1, end);
for(int i = start; i <= end; i++) {
tmp[i] = arr[i];
}
int k = start;
int index1 = start;
int index2 = m + 1;
while (index1 <= m && index2 <= end) {
if(tmp[index1] > tmp[index2]) {
arr[k] = tmp[index2];
count = count + index2 - k;
k++;
index2++;
} else {
arr[k] = tmp[index1];
k++;
index1++;
}
}
while (index1 <= m) {
arr[k] = tmp[index1];
k++;
index1++;
}
while (index2 <= end) {
arr[k] = tmp[index2];
k++;
index2++;
}
}
}
맞았다.. long과 int도 잘 고려해서 풀어야 한다는 걸 이번 문제에서 배웠다. 앞으로 그냥 다 long으로 해서 푸는 게 나을 것 같다.