https://www.acmicpc.net/problem/1517
부분 배열 A, 부분 배열 B를 머지할때 각 인덱스를 i, j로 두고 머지하되
A[i] > B[j]인 경우 SWAP이 발생하는데 이때 SWAP 횟수는MID(=(start + end)/2) - i + 1
이 된다.
import java.io.*;
import java.util.*;
public class Main {
public static BufferedReader br;
public static BufferedWriter bw;
public static int N;
public static int[] arr, arr2;
public static void input() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
N = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
arr = new int[N];
arr2 = new int[N];
for (int i = 0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
}
public static long caculate(int start, int end) {
if (start == end) return 0;
int mid = (start + end) / 2;
//divide
long result = caculate(start, mid) + caculate(mid + 1, end);
int i = start;
int j = mid + 1;
int ind = 0;
//부분 배열 합쳐줌
while (i <= mid || j <= end) {
if (i <= mid && (j > end || arr[i] <= arr[j])) {
arr2[ind++] = arr[i++];
} else {
result += (mid - i + 1);
arr2[ind++] = arr[j++];
}
}
//원래 배열에 결과 반영
for (ind = start; ind <= end; ind++)
arr[ind] = arr2[ind - start];
return result;
}
public static void solve() throws IOException {
bw.write(caculate(0, N-1) + "\n");
bw.flush();
}
public static void main(String[] args) throws IOException {
input();
solve();
}
}