我需要帮助解决这个名为FlipSort的UVA问题。我使用O(nlogn)方法使用反演,测试用例很好。但我不知道为什么我仍然收到RuntimeError
。这是我的Java代码。
import java.io.*;
import java.util.*;
import java.math.*;
class Main {
static int flips = 0;
public static void main(String... args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String line;
while ((line = in.readLine()) != null) {
BigInteger[] numbers = getNumbers(in.readLine());
String ans = getAns(numbers);
System.out.println(ans);
}
}
static String getAns(BigInteger[] numbers) {
flips = 0;
mergeSort(numbers);
return "Minimum exchange operations : " + flips;
}
static BigInteger[] mergeSort(BigInteger[] numbers) {
if (numbers.length <= 1) return numbers;
int n = numbers.length;
BigInteger[] p1 = mergeSort(subArray(numbers, 0, n/2));
BigInteger[] p2 = mergeSort(subArray(numbers, n/2, n));
return merge(p1, p2);
}
static BigInteger[] merge(BigInteger[] p1, BigInteger[] p2) {
BigInteger[] ans = new BigInteger[p1.length+p2.length];
int i = 0, j = 0, k = 0;
while (i < p1.length || j < p2.length) {
if (i < p1.length && j < p2.length) {
if (p1[i].compareTo(p2[j]) <= 0) {
ans[k] = p1[i];
i++;
} else {
flips++;
ans[k] = p2[j];
j++;
}
} else if (i < p1.length) {
ans[k] = p1[i];
i++;
} else if (j < p2.length) {
ans[k] = p2[j];
j++;
}
k++;
}
return ans;
}
static BigInteger[] subArray(BigInteger[] numbers, int start, int end) {
BigInteger[] ans = new BigInteger[end-start];
for (int i = start; i < end; i++)
ans[i-start] = numbers[i];
return ans;
}
static BigInteger[] getNumbers(String line) {
String[] vals = line.split(" ");
BigInteger[] ans = new BigInteger[vals.length];
for (int i = 0; i < ans.length; i++)
ans[i] = new BigInteger(vals[i]);
return ans;
}
}