During Frosh Week, students play various fun games to get to know each other and compete against other teams. In one such game, all the frosh on a team stand in a line, and are then asked to arrange themselves according to some criterion, such as their height, their birth date, or their student number. This rearrangement of the line must be accomplished only by successively swapping pairs of consecutive students. The team that finishes fastest wins. Thus, in order to win, you would like to minimize the number of swaps required.
Input Specification
Input contains several test cases. For each test case, the first line of input contains one positive integer n, the number of students on the team, which will be no more than one million. The following n lines each contain one integer, the student number of each student on the team. No student number will appear more than once.Sample Input
3 3 1 2
Output Specification
For each test case, output a line containing the minimum number of swaps required to arrange the students in increasing order by student number.Output for Sample Input
2结果用long 表示,用int提交几次总是WA
归并排序求逆序数
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class Main implements Runnable
{
private static final boolean DEBUG = false;
private PrintWriter cout;
private Scanner cin;
private int n;
private int[] num, tmp;
private void init()
{
try {
if (DEBUG) {
cin = new Scanner(new BufferedInputStream(new FileInputStream("d:\\OJ\\uva_in.txt")));
} else {
cin = new Scanner(new BufferedInputStream(System.in));
}
cout = new PrintWriter(new OutputStreamWriter(System.out));
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean input()
{
if (!cin.hasNextInt()) return false;
n = cin.nextInt();
num = new int[n];
for (int i = 0; i < n; i++) {
num[i] = cin.nextInt();
}
tmp = new int[n];
return true;
}
private long mergesort(int l, int r, int[] a)
{
if (l >= r) return 0;
int m = (l + r) >> 1;
long s1 = mergesort(l, m, a);
long s2 = mergesort(m + 1, r, a);
int p = l, q = m + 1;
int k = l;
long sum = s1 + s2;
while (p <= m || q <= r) {
if (p > m || (q <= r && a[p] > a[q])) {
tmp[k++] = a[q++];
sum += m + 1 - p;
} else {
tmp[k++] = a[p++];
}
}
for (int i = l; i <= r; i++) {
a[i] = tmp[i];
}
return sum;
}
private void solve()
{
long ans = mergesort(0, n - 1, num);
cout.println(ans);
cout.flush();
}
public void run()
{
init();
while (input()) {
solve();
}
}
public static void main(String[] args)
{
new Thread(new Main()).start();
}
}