-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountInv.cpp
More file actions
76 lines (66 loc) · 1.3 KB
/
CountInv.cpp
File metadata and controls
76 lines (66 loc) · 1.3 KB
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
71
72
73
74
75
// UVA: 10810
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace std;
long long CountInvMerge(long long* a, int n)
{
int mid = (n+1)/2;
int i = 0, j = mid;
int k = 0; //index of sorted array
long long inv_cnt = 0;
long long* sorted = new long long[n];
while (i<mid || j<n)
{
if(i>=mid && j<n)
{
sorted[k++] = a[j++];
}
else if((j >= n && i < mid)||(a[i] < a[j]))
{
sorted[k++]=a[i++];
}
else if(a[j] < a[i])
{
sorted[k++] = a[j++];
inv_cnt += (mid-i);
}
for(int q=0; q<n; q++)
{
a[q] = sorted[q];
}
delete[] sorted;
return inv_cnt;
}
}
long long CountInv(long long* a, int n)
{
if(n<=1)
{
return 0;
}
int mid = (n+1)/2;
long long res = 0;
res += CountInv(a, mid);
res += CountInv(a+mid, n-mid);
res += CountInvMerge(a, n);
return res;
}
int main()
{
int n ;
long long res;
while (cin>>n && n)
{
long long* arr = new long long[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
res = CountInv(arr, n);
cout<<res<<endl;
delete[] arr;
}
return 0;
}