-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergecorrect.cpp
More file actions
71 lines (67 loc) · 1.33 KB
/
mergecorrect.cpp
File metadata and controls
71 lines (67 loc) · 1.33 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
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <stack>
using namespace std;
long long ans;
int a[1000000];
void merge(int *a , int first, int mid, int last)
{
int * temp = new int[last - first + 1];
int first1 = first, last1 = mid;
int first2 = mid + 1, last2 = last;
int index = 0;
while(first1 <= last1 && first2 <= last2)
{
if(a[first1 ] <= a[first2])
{
temp[index++] = a[first1++];
}
else
{
ans += last1 - first1 + 1;
temp[index++] = a[first2++];
}
}
while(first1 <= last1)
{
temp[index++] = a[first1++];
}
while(first2 <= last2)
{
temp[index++] = a[first2++];
}
int i;
for(i = first; i <= last; i++)
{
a[i] = temp[i - first];
}
delete [] temp;
return;
}
void inv_pair(int *a, int first, int last)
{
if(last - first > 0)
{
int mid = (last + first) / 2;
inv_pair(a, first, mid);
inv_pair(a, mid + 1, last);
merge(a, first, mid, last);
}
return;
}
int main()
{
int n, i;
while(cin >> n && n!=0)
{
ans = 0;
for(i = 0; i < n; i++)
cin >> a[i];
inv_pair(a, 0, n - 1);
cout << ans << endl;
}
return 0;
}