题目:http://acm.hdu.edu.cn/showproblem.php?pid=3743
Frosh Week
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2265 Accepted Submission(s): 714
Problem Description
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
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.
Output
Output a line containing the minimum number of swaps required to arrange the students in increasing order by student number.
Sample Input
Sample Output
分析:求解相邻交换的次数使得所有的数字呈现单调排列。交换的次数也就是原数列的逆序数。
在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。逆序数为偶数的排列称为偶排列;逆序数为奇数的排列称为奇排列。如2431中,21,43,41,31是逆序,逆序数是4,为偶排列。
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=1e6+10;
int a[maxn],b[maxn];
long long sum;
void merge(int sdex,int mdex,int edex){
int i=sdex,j=mdex+1,k=sdex;
while(i<=mdex&&j<=edex){
if(a[i]<a[j]) b[k++]=a[i++];
else b[k++]=a[j++],sum+=(mdex+1-i);
} //eg: 2,3 1,4 -->1,2,3,4 1越过2,3两个位置即(mdex+1-i)
while(i!=mdex+1) b[k++]=a[i++];
while(j!=edex+1) b[k++]=a[j++];
for(i=sdex;i<=edex;i++) a[i]=b[i];
}
void mergesort(int sdex,int edex){
int mdex;
if(sdex<edex){
mdex=(sdex+edex)/2;
mergesort(sdex,mdex);
mergesort(mdex+1,edex);
merge(sdex,mdex,edex);
}
}
int main()
{
int n,i;
while(cin>>n){
sum=0;
for(i=0;i<n;i++) scanf("%d",&a[i]);
mergesort(0,n-1);
printf("%lld\n",sum);
}
return 0;
}