在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。
如2 4 3 1中,2 1,4 3,4 1,3 1是逆序,逆序数是4。给出一个整数序列,求该序列的逆序数。
Input
第1行:N,N为序列的长度(n <= 50000) 第2 - N + 1行:序列中的元素(0 <= A[i] <= 10^9)
Output
输出逆序数
Input示例
4 2 4 3 1
Output示例
4
这道题暴力的话会超时,看了下网上的代码,需要用到归并
#include<cstdio> int main() { int a[50005]; int count=0; int n; while(~scanf("%d",&n)) { count=0; for(int i=0;i<n;i++) scanf("%d",a+i); for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) if(a[i]>a[j]) count++; printf("%d\n",count); } return 0; }
需要用到归并
时间复杂度为O(NlogN)。
先把代码写下,详细的理解稍后补充
#include<cstdio> #include<cstring> //#include<algorithm> using namespace std; typedef long long ll; const int maxn=50005; int a[maxn],b[maxn]; int count; int n; void merge(int a[],int start,int mid,int end) { int i=start,j=mid+1,k=start; while(i<=mid&&j<=end) { if(a[i]<=a[j]) { b[k++]=a[i++]; } else { count+=j-k; b[k++]=a[j++]; } } while(i<=mid) { b[k++]=a[i++]; } while(j<=end) { b[k++]=a[j++]; } for(int i=start;i<=end;i++) { a[i]=b[i]; } } void mergesort(int *a,int start,int end) { if(start<end) { int mid=(start+end)/2; mergesort(a,start,mid); mergesort(a,mid+1,end); merge(a,start,mid,end); } } int main() { while(~scanf("%d",&n)) { for(int i=0;i<n;i++) scanf("%d",a+i); count=0; mergesort(a,0,n-1); printf("%d\n",count); } return 0; }