-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest51.cpp
70 lines (56 loc) · 956 Bytes
/
test51.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int InversePairsCore(int a[],int beg,int end)
{
if(beg==end)
return 0;
int mid=(beg+end)/2;
int left=InversePairsCore(a,beg,mid);
int right=InversePairsCore(a,mid+1,end);
int cnt=0;
int i=mid;
int j=end;
int *tmp=new int[end-beg+1]();
int index=end-beg;
while(i>=beg && j>mid)
{
if(a[i]>a[j])
{
cnt+=j-mid;
tmp[index--]=a[i--];
}
else
{
tmp[index--]=a[j--];
}
}
while(i>=beg)
tmp[index--]=a[i--];
while(j>mid)
tmp[index--]=a[j--];
index=0;
for(int i=beg;i<=end;++i)
a[i]=tmp[index++];
delete[] tmp;
return left+right+cnt;
}
int InversePairs(int a[],int len)
{
if(!a || len<=0)
{
return 0;
}
return InversePairsCore(a,0,len-1);
}
int main()
{
// int a[]={7,5,6,4};
// int a[]={1,2,3,4,5,6};
// int a[]={5,4,3,4,2,1,3,5};
int a[]={5};
int len=sizeof(a)/sizeof(a[0]);
cout<<InversePairs(a,len)<<endl;
return 0;
}