Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n = in.nextInt();
- int[] nums = new int[n];
- for (int i = 0; i < n; i++) {
- nums[i] = in.nextInt();
- }
- System.out.println(countInversions(nums));
- }
- public static long countInversions(int[] nums) {
- return mergeSort(nums, 0, nums.length - 1);
- }
- public static long mergeSort(int[] arr, int left, int right) {
- // If the subarray has only one element,
- // it doesn't have any inversions within it.
- if (left == right) return 0;
- int mid = (left + right) / 2;
- long result = 0;
- // Count all inversions such that the first element
- // is in the left half [left; mid] and the second is, too.
- result += mergeSort(arr, left, mid);
- // Count all inversions such that the first element
- // is in the right half [mid + 1; right] and the second is, too.
- result += mergeSort(arr, mid + 1, right);
- // Count all inversions such that the first element
- // is in the left half [left; mid] and the second
- // is in the right half [mid + 1; right].
- result += mergeSortedArrays(arr, left, right);
- return result;
- }
- public static long mergeSortedArrays(int[] arr, int left, int right) {
- int len = right - left + 1;
- int[] tmp = new int[len];
- int mid = (left + right) / 2;
- long inversions = 0;
- for (int k = 0, i = left, j = mid + 1; k < len; k++) {
- if (i > mid) tmp[k] = arr[j++];
- else if (j > right) tmp[k] = arr[i++];
- else if (arr[i] < arr[j]) tmp[k] = arr[i++];
- else {
- tmp[k] = arr[j++];
- // Elements at indices [i; mid] from the left half
- // are forming inversions with the element at index j
- // in the right half, e.g. (arr[i], arr[j]) is an inversion,
- // (arr[i + 1], arr[j]) is an inversion, ..., (arr[mid], arr[j]) is an inversion.
- // Hence, (mid - i + 1) inversions
- // are added to the total count of inversions such that
- // the first element is in the left half [left; mid] and
- // the second is in the right half [mid + 1; right].
- inversions += mid - i + 1;
- }
- }
- for (int k = 0, i = left; k < len; k++, i++) {
- arr[i] = tmp[k];
- }
- return inversions;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement