-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMerge_Sort.cpp
More file actions
85 lines (77 loc) · 1.31 KB
/
Copy pathMerge_Sort.cpp
File metadata and controls
85 lines (77 loc) · 1.31 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
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <cstring>
#include <iomanip>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <string>
#include <vector>
#include <new>
#include <bitset>
using namespace std;
#define ll long long int
#define INF 2147483647
#define PI acos(-1.0)
#define EPS 1e-9
template <typename X> X gcd(X a, X b){if(!b)return a; else return gcd(b, a%b);}
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef pair<ll, ll> llp;
typedef pair<double, double> dd;
typedef pair<char, int> ci;
int n, i;
ll ans;
int a[1000010], b[1000010];
void merge(int l1, int r1, int l2, int r2)
{
int x=l1, y=l2, xx=1;
int pos=0;
while(x<=r1 && y<=r2)
{
if(a[x]>a[y])
{
b[pos++]=a[y++];
ans+=(ll)((r1-l1+2)-xx);
}
else
{
b[pos++]=a[x++];
xx++;
}
}
while(x<=r1)
b[pos++]=a[x++];
while(y<=r2)
b[pos++]=a[y++];
pos=0;
for(i=l1;i<=r2;++i)
a[i]=b[pos++];
}
void merge_sort(int low, int high)
{
if(low<high)
{
int center=(low+high)>>1;
merge_sort(low, center);
merge_sort(center+1, high);
merge(low, center, center+1, high);
}
}
int main()
{
while(scanf("%d", &n)!=EOF)
{
ans=0;
for(i=0;i<n;++i)
scanf("%d", &a[i]);
merge_sort(0, n-1);
printf("%lld\n", ans);
}
return 0;
}