180. Inversions
time limit per test: 0.5 sec.
memory limit per test: 4096 KB
memory limit per test: 4096 KB
input: standard
output: standard
output: standard
There are N integers (1<=N<=65537) A1, A2,.. AN (0<=Ai<=10^9). You need to find amount of such pairs (i, j) that 1<=i<j<=N and A[i]>A[j].
Input
The first line of the input contains the number N. The second line contains N numbers A1...AN.
Output
Write amount of such pairs.
Sample test(s)
Input
5
2 3 1 5 4
2 3 1 5 4
Output
3
逆序对统计,就当复习下归排吧。。
贴代码:
逆序对统计,就当复习下归排吧。。
贴代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<algorithm>
#include<vector>
#include<cstdlib>
#define inf 0xfffffff
#define CLR(a,b) memset((a),(b),sizeof((a)))
#define FOR(a,b) for(int a=1;a<=(b);(a)++)
using namespace std;
int const nMax = 70010;
int const base = 10;
typedef int LL;
typedef pair<LL,LL> pij;
// std::ios::sync_with_stdio(false);
int a[nMax],c[nMax];
long long ans;
int n;
void merge_sort(int l,int r){
if(l==r) return ;
int mid=(l+r)>>1;
merge_sort(l,mid);
merge_sort(mid+1,r);
int i=l,j=mid+1,k=0;
while(i<=mid&&j<=r) {
if(a[i]>a[j]) ans+=(mid-i+1);
if(a[i]<=a[j]) c[k++]=a[i++];
else c[k++]=a[j++];
}
while(i<=mid)c[k++]=a[i++];
while(j<=r) c[k++]=a[j++];
for(i=0;i<k;i++) a[l+i]=c[i];
return ;
}
int main(){
scanf("%d",&n);
FOR(i,n) scanf("%d",&a[i]);
ans=0;
merge_sort(1,n);
printf("%I64d\n",ans);
return 0;
}