兔子的逆序对(归并排序求逆序对)

兔子的逆序对

import java.util.Scanner;

public class 兔子的逆序对 {

	static long ans = 0;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			int n = sc.nextInt();
			int[] arr = new int[n];
			for (int i = 0; i < arr.length; i++) {
				arr[i] = sc.nextInt();
			}
			int m = sc.nextInt();
			sort(arr, 0, arr.length - 1);
			ans %= 2;// ans表示为逆序对的奇偶性
			for (int i = 0; i < m; i++) {
				int l = sc.nextInt();
				int r = sc.nextInt();
				if (((r - l + 1) * (r - l) / 2) % 2 != 0) {// 参数为偶数则ans的奇偶性不变
					ans = 1 - ans;// 在0-1间滚动地变化
				}
				if (ans % 2 == 0) {
					System.out.println("like");
				} else {
					System.out.println("dislike");
				}
			}
		}
	}

	private static void sort(int[] arr, int begin, int end) {
		int[] helper = new int[arr.length];
		mergeSort(arr, helper, begin, end);
	}

	private static void mergeSort(int[] arr, int[] helper, int begin, int end) {
		if (begin >= end) {
			return;
		}
		int mid = (begin + end) / 2;
		mergeSort(arr, helper, begin, mid);
		mergeSort(arr, helper, mid + 1, end);
		merge(arr, helper, begin, end);
	}

	private static void merge(int[] arr, int[] helper, int begin, int end) {
		int p = begin;
		int mid = (begin + end) / 2;
		int q = mid + 1;
		int cur = begin;
		while (p <= mid && q <= end) {
			if (arr[p] <= arr[q]) {
				helper[cur++] = arr[p++];
			} else {
				ans += mid - p + 1;
				helper[cur++] = arr[q++];
			}
		}
		while (p <= mid) {
			helper[cur++] = arr[p++];
		}
		while (q <= end) {
			helper[cur++] = arr[q++];
		}
		for (int i = begin; i <= end; i++) {
			arr[i] = helper[i];
		}
	}

}

只能通过60%的测试数据,可能是数据读入太慢?

你可能感兴趣的:(OJ)